Created
December 25, 2022 05:30
-
-
Save thmain/0e6165b35496f2b12da97b7b73ed9d13 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function lengthOfLongestSubstring(s) { | |
if (s.length <= 1) | |
return s.length | |
let lookup = new Map() | |
let len = s.length | |
let max = 0 | |
let start = 0 | |
for (let i = 0; i < len; i++) { | |
let c = s.charAt(i) | |
if (lookup.has(c) && lookup.get(c) >= start) { | |
start = lookup.get(c) + 1; // Read the logic in the notes above | |
} | |
lookup.set(c, i) | |
max = Math.max(max, i - start + 1) | |
} | |
return max; | |
} | |
console.log(lengthOfLongestSubstring('OBAMACARE')) // 4 | |
console.log(lengthOfLongestSubstring('ABBA')) // 2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment