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

LeetCode:Longest Substring Without Repeating Characters

很多 時間 最大的 example {} int char ring dex

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.

題目讀起來很簡單,一開始做的時候也很自信,但是提交了很多次都失敗了。

思路:

  1. 最長不重復子串,暴力方法就是遍歷所有的子串,並檢查是否有重復的子串,但是這種時間上復雜度很高,被pass
  2. 用dp[j]來表示子串0-j中最長不重復子串,那麽則存在兩種狀態:
    • s[j]在start之後,j前面出現,此時dp[j] = j - start -1 (start 為s[j]之前最後出現的位置)
    • s[j]未出現,此時dp[j] = dp[j-1] + 1;
  3. dp中最大的即為最長的不重復子串。
 1 class
Solution: 2 def lengthOfLongestSubstring(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 dp = {-1:0} 8 i = 0 9 index = 0 10 maxLen = 0; 11 temp = {} 12 for x in s: 13 if(temp.get(x) != None and temp.get(x) >= index): #
說明在start之後,j之前已經出現過,那麽就重新開始計算。 14 index = temp.get(x) + 1 15 dp[i] = i - temp.get(x); 16 else: 17 dp[i] = dp[i-1] + 1; 18 temp[x] = i 19 maxLen = max(dp[i],maxLen) 20 i += 1 21 return maxLen 22

LeetCode:Longest Substring Without Repeating Characters