尋找最長不重複子串

尋找最長不重複子串

Longest Substring Without Repeating Characters

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

  • Examples:

  • Given "abcabcbb", the answer is "abc", which the length is 3.

  • Given "bbbbb", the answer is "b", with the length of 1.

  • Given "pwwkew", 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.

思路(時間複雜度爲O(n))

  1. 遍歷字符串,過程中將出現過的字符存入字典,key爲字符,value爲字符下標
  2. 用maxLength保存遍歷過程中找到的最大不重複子串的長度
  3. 用start保存最長子串的開始下標
  4. 如果字符已經出現在字典中,更新start的值
  5. 如果字符不在字典中,更新maxLength的值
  6. return maxLength

代碼

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = maxLength = 0
        usedChar = {}

        for i in range(len(s)):
            if s[i] in usedChar and start <= usedChar[s[i]]:
                start = usedChar[s[i]] + 1
            else:
                maxLength = max(maxLength, i - start + 1)
            usedChar[s[i]] = i

        return maxLength

本題以及其它leetcode題目代碼github地址: github地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章