思路

使用一个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[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

phiysng
1 声望1 粉丝

K.I.S.S