class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)]
# 把s转为列表
copy = list(s) # 空间复杂度O(n) 时间复杂度O(n)
length = 0
for left in range(n):
window = []
# left和right指针分别指向滑动窗口的两端
# 先向右移动right,直到移动不了为止,比较并记下length
# 然后移动left,生成新窗口,重新进行上述操作
if copy[left] not in window:
window.append(copy[left])
right = left+1
while right < n and copy[right] not in window:
window.append(copy[right])
right += 1
if length < len(window):
length = len(window)
return length
官网答案更好一点
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
window = set() # 用set更妙,这样不用每次在left循环的时候,都要使window=[]
n = len(s)
max_len = 0
right = 0
for left in range(0, n):
if left > 0:
window.remove(s[left-1])
# right = left 注意这个right应该在for left外面初始化
# 每次遇到重复的数字,则只需要把left左移(并remove(s[left-1])),
# 而right不变,因为下次循环还要继续判断right是否要加入window
while right < n and s[right] not in window:
window.add(s[right])
right += 1
if max_len < len(window):
max_len = len(window)
return max_len