Advertisement
iko1133

Untitled

Dec 23rd, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var lengthOfLongestSubstring = function(s) {
  6. if(s.length < 2) return s.length;
  7.  
  8. let seenChars = {};
  9. let startId = 0;
  10. let maxLength = 0;
  11. let currLength = 0;
  12.  
  13. for(let i = 0; i < s.length; i++){
  14. const currChar = s[i];
  15.  
  16. if(seenChars[currChar] !== undefined) {
  17. currLength = i - startId;
  18. if(currLength > maxLength) maxLength = currLength;
  19. startId = seenChars[currChar] + 1;
  20. seenChars[currChar] = i;
  21.  
  22. const keys = Object.keys(seenChars);
  23.  
  24. for(let j = 0; j < keys.length; j++){
  25. const seenCharValue = seenChars[keys[j]];
  26. if(seenCharValue < startId) seenChars[keys[j]] = undefined;
  27. }
  28. } else {
  29. seenChars[currChar] = i;
  30. }
  31. }
  32.  
  33. if(s.length - startId > maxLength) return s.length - startId;
  34. return maxLength;
  35. };
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement