Advertisement
satishfrontenddev4

Untitled

Jan 6th, 2024
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a string, find the length of the longest substring which has no repeating characters.
  3.  
  4. Input format
  5. Input is a string.
  6.  
  7. Output format
  8. Output is an integer representing the longest substring with no repeating characters.
  9.  
  10. Sample Input 1
  11. aabcccbcb
  12.  
  13. Sample Output 1
  14. 3
  15.  
  16. Explanation 1
  17. "abc" is the longest substring with no repeating characters.
  18.  
  19. Sample Input 2
  20. cdddddd
  21.  
  22. Sample Output 2
  23. 2
  24.  
  25. Explanation 2
  26. "cd" is the longest substring with no repeating characters.
  27. */
  28.  
  29. /**
  30.  * @param {string} str
  31.  * @return {number}
  32.  */
  33. // please check general approach of this video: https://www.youtube.com/watch?v=Lav6St0W_pQ
  34. function longestSubstringWithoutRepeatingCharacter(str) {
  35.     let i,j,currLongestSubstring,longestSubstring,n;
  36.     i=0;
  37.     j=0;
  38.     currLongestSubstring='';
  39.     longestSubstring='';
  40.     n=str.length;
  41.     const mp= new Map();
  42.     while(j<n){
  43.         const currChar=str.charAt(j);
  44.         if(!mp.has(currChar)){
  45.             mp.set(currChar,true);
  46.             currLongestSubstring=str.slice(i,j+1);
  47.             if(currLongestSubstring.length>longestSubstring.length)
  48.               longestSubstring=currLongestSubstring;
  49.         }
  50.         else{
  51.             while(mp.has(currChar)){
  52.                 mp.delete(str.charAt(i));
  53.                 i++;
  54.             }
  55.             mp.set(currChar,true);// j-th index character
  56.             currLongestSubstring=str.slice(i,j+1);
  57.             if(currLongestSubstring.length>longestSubstring.length)
  58.               longestSubstring=currLongestSubstring;
  59.         }
  60.         j++;
  61.     }
  62.     return longestSubstring.length;
  63.  
  64. }
  65.  
  66. function main() {
  67.     let s = readLine();
  68.     let result = longestSubstringWithoutRepeatingCharacter(s);
  69.     console.log(result);
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement