3. Longest Substring Without Repeating Characters

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.

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         if(s.empty()){
 5             return 0;
 6         }
 7         int max=1;
 8         unordered_map<char,int> pos;
 9         int start=0;
10         
11         for(int i=0;i<s.size();i++){
12             if(pos.find(s[i])!=pos.end()){
13                 
14                 int tmp = pos.size();
15                 max=tmp>max?tmp:max;
16                 int newstart=pos[s[i]]+1;
17                 for(int j=start;j<=pos[s[i]];j++){
18                     pos.erase(s[j]);
19                 }
20                 start=newstart;
21             }
22             
23             pos[s[i]]=i;
24         }
25         
26         int tmp = pos.size();
27         max=tmp>max?tmp:max;
28         return max;
29     }
30 };

grandyang解法一:

滑动窗口问题,用两个指针分别代表窗口的两端,保证窗口里的字母都不相同。

hash table用来存字母上一次出现的index。

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int res = 0, left = -1, n = s.size();
 5         unordered_map<int, int> m;
 6         for (int i = 0; i < n; ++i) {
 7             if (m.count(s[i]) && m[s[i]] > left) {
 8                 left = m[s[i]];  
 9             }
10             m[s[i]] = i;
11             res = max(res, i - left);            
12         }
13         return res;
14     }
15 };

grandyang解法二:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         vector<int> m(128, -1);
 5         int res = 0, left = -1;
 6         for (int i = 0; i < s.size(); ++i) {
 7             left = max(left, m[s[i]]);
 8             m[s[i]] = i;
 9             res = max(res, i - left);
10         }
11         return res;
12     }
13 };

 

posted @ 2019-01-01 03:57  回到明天  阅读(113)  评论(0编辑  收藏  举报