LeetCode 3. Longest Substring Without Repeating Characters 滑动窗口
Given a string s
, find the length of the longest substring without repeating characters.
Solution
用一个 \(dict\) 来映射字符的次数。然后用 \(left\), \(right\) 来决定window的大小。
点击查看代码
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
window = {}
left = 0
right = 0
ans = 0
while right<len(s):
c = s[right]
right+=1
if c not in window:
window[c] = 1
else:
window[c]+=1
while window[c]>1:
tmp = s[left]
left+=1
window[tmp]-=1
ans=max(ans, right-left)
return ans