Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Save thmain/0e6165b35496f2b12da97b7b73ed9d13 to your computer and use it in GitHub Desktop.
Save thmain/0e6165b35496f2b12da97b7b73ed9d13 to your computer and use it in GitHub Desktop.
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