Scott's Blog

学则不固, 知则不惑

0%

算法题: 无重复字符串的最长子串

📌 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def lengthOfLongestSubstring(s: str) -> int:
seen = {}
l = 0
output = 0
for r in range(len(s)):
"""
If s[r] not in seen, we can keep increasing the window size by moving right pointer
"""
if s[r] not in seen:
output = max(output, r-l+1)
else:
# There are two cases if s[r] in seen:
# case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1.
# case2: s[r] is not inside the current window, we can keep increase the window
if seen[s[r]] < l:
output = max(output,r-l+1)
else:
l = seen[s[r]] + 1
seen[s[r]] = r

return output


lengthOfLongestSubstring("pwwkew")