使用一個idx
指明當前子串的開始位置python
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[c] < idx: pass else: res = max(res , i - idx) idx = m[c] + 1 m[c] = 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[c] >= idx: res = max(res , i - idx) idx = m[c] + 1 m[c] = i res = max(res , i - idx + 1) return res