1. 程式人生 > >LeetCode3:Longest Substring Without Repeating Characters

LeetCode3:Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:

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

Example 2:

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

Example 3:

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.

LeetCode:連結

“滑動視窗法”:變數start和end分別記錄子串的起點和終點,從左向右逐字元遍歷原始字串,每次將end + 1。字典countDict儲存當前子串中各字元的個數。當新增字元c的計數 > 1時,向右移動起點start,並將s[start]在字典中的計數 - 1,直到countDict[c]不大於1為止
。時刻更新最大長度。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start, end, ans = 0, 0, 0
        countDict = {}
        for c in s:
            end += 1
            countDict[c] = countDict.get(c, 0) + 1
            # 說明子串中有重複的字元 必須去除
            while countDict[c] > 1:
                countDict[s[start]] -= 1
                start += 1
            ans = max(ans, end-start)
        return ans