Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a string, find the length of the longest substring which has no repeating characters.
- Input format
- Input is a string.
- Output format
- Output is an integer representing the longest substring with no repeating characters.
- Sample Input 1
- aabcccbcb
- Sample Output 1
- 3
- Explanation 1
- "abc" is the longest substring with no repeating characters.
- Sample Input 2
- cdddddd
- Sample Output 2
- 2
- Explanation 2
- "cd" is the longest substring with no repeating characters.
- */
- /**
- * @param {string} str
- * @return {number}
- */
- // please check general approach of this video: https://www.youtube.com/watch?v=Lav6St0W_pQ
- function longestSubstringWithoutRepeatingCharacter(str) {
- let i,j,currLongestSubstring,longestSubstring,n;
- i=0;
- j=0;
- currLongestSubstring='';
- longestSubstring='';
- n=str.length;
- const mp= new Map();
- while(j<n){
- const currChar=str.charAt(j);
- if(!mp.has(currChar)){
- mp.set(currChar,true);
- currLongestSubstring=str.slice(i,j+1);
- if(currLongestSubstring.length>longestSubstring.length)
- longestSubstring=currLongestSubstring;
- }
- else{
- while(mp.has(currChar)){
- mp.delete(str.charAt(i));
- i++;
- }
- mp.set(currChar,true);// j-th index character
- currLongestSubstring=str.slice(i,j+1);
- if(currLongestSubstring.length>longestSubstring.length)
- longestSubstring=currLongestSubstring;
- }
- j++;
- }
- return longestSubstring.length;
- }
- function main() {
- let s = readLine();
- let result = longestSubstringWithoutRepeatingCharacter(s);
- console.log(result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement