LeetCode 3. Longest Substring Without Repeating Characters(medium難度)【精】
阿新 • • 發佈:2017-12-07
scrip 有一個 重復 and 指向 是否 最長 ring 最優解
is a subsequence and not a substring.
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"
題目很通俗易懂,就是找一個字符串中,沒有重復字符的最長子串的長度。說實話,這道中等難度的題目卡了我很久,最後把它想明白時,內心還是有些小小的激動的。其實不僅是刷題,人生中很多其他方面的事情也都需要有一個積極的心態,不斷給自己積極的心理暗示,這樣結果一般真的就能如你所願。
回歸正題,這道題暴力搜索法復雜度是O(n^3),這也很好理解,兩個指針分別指向字符串的首尾,兩重循環,每次都需要判斷兩個指針之間是否有重復的字符,我們在面試時可以第一時間向面試官講出這樣的思路,至少可以從側面展現出我們思維敏捷的特點,後續的改進再聊。刷題時,這個復雜度肯定會超時,我們需要進一步改進它。我這裏直接把最優解的代碼貼出來,時間復雜度為O(n)之後我再解釋為何這樣做,代碼如下:
1 class Solution {
2 public:
3 int lengthOfLongestSubstring(string s) {
4 //這道題目還是很不錯的,參考著優秀解答寫一般,O(n)復雜度,以空間換時間。
5 vector<int> mymap(256,-1);
6 int i,last=0,ans=0;
7 for (int i = 0; i < s.length(); i++)
8 {
9 if (mymap[s[i]] == -1 || mymap[s[i]] < last) //如果該字符沒有出現過
10 ans = max(ans, i - last + 1);
11 else
12 last = mymap[s[i]] + 1;
13 mymap[s[i]] = i;
14 }
15 return ans;
16
17 }
18 };
解釋一下思路:last表示字符串開始的位置,
LeetCode 3. Longest Substring Without Repeating Characters(medium難度)【精】