使用滑动窗口计算无重复字符的最长子串:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-dong-chuang-kou-by-powcai/
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
left = 0
max_len, cur_len = 0, 0
temp_set = set()
n = len(s)
for i in range(n):
cur_len += 1
if s[i] in temp_set:
temp_set.remove(s[left])
left += 1
cur_len -= 1
max_len = max(max_len, cur_len)
temp_set.add(s[i])
return max_len
其中if错误,应当改为while
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
lookup.remove(s[left])
left += 1
cur_len -= 1
if cur_len > max_len:max_len = cur_len
max_len = max(max_len, cur_len)
lookup.add(s[i])
return max_len