Longest Substring Without Repeating Characters
LeetCode 3 · View on LeetCode
Variable-size window with a map tracking the last index of each character. When a duplicate is found, jump the left pointer past it.
package main
import "fmt"
func lengthOfLongestSubstring(s string) int {
seen := make(map[byte]int)
maxLen, left := 0, 0
for right := 0; right < len(s); right++ {
if idx, ok := seen[s[right]]; ok && idx >= left {
left = idx + 1
}
seen[s[right]] = right
if right-left+1 > maxLen {
maxLen = right - left + 1
}
}
return maxLen
}
func main() {
fmt.Println(lengthOfLongestSubstring("abcabcbb")) // 3
fmt.Println(lengthOfLongestSubstring("bbbbb")) // 1
fmt.Println(lengthOfLongestSubstring("pwwkew")) // 3
}