3. Longest Substring Without Repeating Characters

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        maxLen = 0
        
        i, j = 0, 0
        while j < len(s):
            # 更新条件:新进元素在window里重复
            while s[j] in s[i:j]:
                maxLen = max(maxLen, j-i)
                i += 1
                
            j += 1
        maxLen = max(maxLen, j-i)
        return maxLen

12/30/2020 Update

重写的时候第一反应用了 index 函数,好处是更新一步到位,在Python中不用反复切片string。但这个写法需要维护 window,worse case 的时间复杂度是O(N).

P.S. 最后多的一次 max 比较确实很容易忘掉。

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        res, window = 0, ""
        for ch in s:
            if ch in window:
                res = max(res, len(window))
                window = window[window.index(ch)+1:] + ch
            else:
                window += ch
        res = max(res, len(window))
        return res

Last updated

Was this helpful?