1. 程式人生 > >leetcode:[3]最長不含重復字符子串

leetcode:[3]最長不含重復字符子串

hat lee sub 重復字符 clas def 出現 ascii碼表 asc

  • Input: "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3.

  • Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.

  • Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3.
    Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
  • class Solution:
        def lengthOfLongestSubstring(self, s):
            """
            遍歷所有字符,通過更新每個字符出現的位置,並調整起點位置,計算得到當前子串的長度。
            :type s: str
            :rtype: int
            """
            # 這裏我們只考慮ascii碼表中的前256個字符,如果輸入是超過這個範圍的則需要擴大list長度
            # 或者使用字典
            char_pos = [-1] * 256
            # 將start標記為當前子串起點前1位。例如當前子串的下表是0-3,則start置為-1,這樣在後面
            # 計算長度的時候就不用+1,因為start標記的是前一位
            start = -1
            maxlen = 0
            # 對每一個字符來說,如果上一次出現的下標比當前子串的起點要大,也就是說這個字符上一次出現
            # 的地方是在start之後,而這一次又出現了,說明在[start+1, i]這一段出現了2個相同字符。
            # 那麽我們需要將start移動到當前字符上一次出現的位置才能確保當前字符的這一次出現是新子串
            # 中的第一次出現。
            # 對於每一個出現的字符,記錄最新出現的下標。
            for i, c in enumerate(s):
                if char_pos[ord(c)] > start:
                    start = char_pos[ord(c)]
    
                char_pos[ord(c)] = i
                maxlen = max(maxlen, i - start)
    
            return maxlen
    

    leetcode:[3]最長不含重復字符子串