標籤:return 開始 c語言 sub substr 分享圖片 not 曆史 for
哎喲我天啊。這道題快折磨死我了。剛開始連題都沒看明白,就是不知道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 maxNums="dvdf"a=Solution()print(a.lengthOfLongestSubstring(s))
我的解釋代碼裡面寫的很清楚。運行效果還不錯
C語言版的先不寫了吧,我已經花了快兩個小時了。按照這個思路寫,完全沒問題。
LeetCode——Problem3:Longest Substring Without Repeating Characters