码迷,mamicode.com
首页 > 其他好文 > 详细

3. Longest Substring Without Repeating Characters

时间:2019-01-01 11:07:51      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:tin   bst   sub   answer   return   hash   style   滑动   substring   

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 };

 

3. Longest Substring Without Repeating Characters

标签:tin   bst   sub   answer   return   hash   style   滑动   substring   

原文地址:https://www.cnblogs.com/ruisha/p/10204122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!