思路
使用一个 idx
指明当前子串的开始位置
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
m = dict()
'''
对于每一个 char c 如果没出现 continue
出现了:
在当前字串的索引之前:continue
之后: map 出现位置之后一位
'''
idx = 0
res = 0
for i , c in enumerate(s):
if c not in m:
pass
else:
if m < idx:
pass
else:
res = max(res , i - idx)
idx = m + 1
m = i
print(res , i - idx + 1)
res = max(res , i - idx + 1)
return res
优化
提取有用的条件分支
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
m = dict()
idx = 0
res = 0
for i , c in enumerate(s):
if c in m and m >= idx:
res = max(res , i - idx)
idx = m + 1
m = i
res = max(res , i - idx + 1)
return res