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

LeetCode——Problem3:Longest Substring Without Repeating Characters

wke 字符串 它的 substring 無重復 character pro 完全 ans

哎喲我天啊。這道題快折磨死我了。剛開始連題都沒看明白,就是不知道substring是什麽意思。研究了好長時間才看出來的。

技術分享圖片

光輝歷史呀。。。菜死了

1、題目

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.
意思就是給一個字符串,找出最長的無重復子串。 比如 “abcabcbb”:他的無重復子串就是“abc”,“abc”,“b” “pwwkew”:它的無重復子串就是“pw”,“wke”,“kew”。最長的長度當然是3啦。而不是“pwke”。因為他要找的是子串,並不是要找的不重復序列。 "dvdf":它的無重復子串就是“dv”,“vdf” 說白了,就是一個字符一個字符的遍歷,找出來沒有重復字符的子字符串。 只是為了看懂這個,就花了好多時間,菜死了。

2、Python解法

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        r=""   #儲存無重復子串
        maxNum=0  #最大無重復子串的長度
        for i in s:
            if i not in r:           #如果不在子串裏,就代表無重復,直接插進去
                r=r+i
            else:                     #
如果在子串裏,就代表重復了,不能直接插進去 if len(r)>maxNum:maxNum=len(r) #先算出來上一個子串的長度 r = r[r.index(i)+1:]+i #把這個相同字符後面的保留。比如"dvdf"。第一個子串是"dv",再遍歷到d的時候,需要把第一個d後面的v保留,再形成一個"vd"子串,這樣還是無重復子串。不保留v的話,就不是一個完整的無重復子串了 if len(r) > maxNum: maxNum = len(r) return maxNum s="dvdf" a=Solution() print(a.lengthOfLongestSubstring(s))

我的解釋代碼裏面寫的很清楚。 運行效果還不錯 技術分享圖片

C語言版的先不寫了吧,我已經花了快兩個小時了。按照這個思路寫,完全沒問題。

LeetCode——Problem3:Longest Substring Without Repeating Characters