3. Longest Substring Without Repeating Characters
Feels like a cheeseburger. One thing that could be improved is to use a set() as a counter instead of a dict.
1class Solution:
2 def lengthOfLongestSubstring(self, s: str) -> int:
3 # classic sliding window
4 # expand r until dupes
5 # shrink l until no dupes
6 # update longest every step
7
8 n = len(s)
9 if not n:
10 return 0
11
12 l = 0
13 r = 0 # inclusive
14 longest = 1
15 deduper = {s[0]: 1}
16
17 while r < n - 1:
18 r += 1
19 if deduper.get(s[r], -1) < 1:
20 deduper[s[r]] = 1
21 longest = max(longest, r - l + 1)
22 else:
23 deduper[s[r]] += 1 # must be 2 now
24 while (
25 deduper[s[r]] > 1 and l < r
26 ): # "l < r" vs. "l <= r" does not matter - either will stop
27 deduper[s[l]] -= 1
28 l += 1
29
30 return longest
#Neetcode150 #Sliding-Window #Python