参考滑动窗口框架自己写的超低效方法:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 滑动窗口 双指针
left = 0
right = 0
window = collections.deque()
res = 0
while right<len(s):
if s[right] not in window:
window.append(s[right])
right += 1
else:
window.popleft()
left+=1
res = max(res,len(window))
return res
另一种同样地思路,只是用的是字典处理
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 滑动窗口 双指针
# 左边从窗口出去,此时要把某个值-1
# 字典存当前的元素存在的个数
left = 0
right = 0
window = {}
res = 0
while right<len(s):
cur = s[right]
if cur not in window:
window[cur] = 0
window[cur] += 1
right += 1
while window[cur]>1:
d = s[left]
window[d] -= 1
left += 1
res = max(res,right-left)
return res