Leetcode003. Longest Substring Without Repeating Characters

 1 ### Letcode 003: Longest Substring Without Repeating Characters
 2 ```
 3 /* basic traverse the string 
 4  * set to predict there is no repeat char in the substring
 5  *
 6  * Time Limit Out
 7  * O(n*n)
 8  */
 9 class Solution {
10 public:
11     int lengthOfLongestSubstring(string s) {
12         int max=0;
13         set<char>diffchar;
14         for(auto it=s.begin();it != s.end();it++)
15         {
16             diffchar.clear();
17             for(auto it1=it;it1!=s.end();it1++)
18             {
19                 if(diffchar.find(*it1) == diffchar.end())diffchar.insert(*it1);
20                 else break;
21             }
22             if(diffchar.size() > max) max = diffchar.size();
23         }
24         return max;
25     }
26 };
27 ```
28 ----------------------------------
29 **learn from ![ACM home](http://www.acmerblog.com/leetcode-solution-longest-substring-without-repeating-characters-6307.html)
30 ```
31 class Solution {
32 public:
33     int lengthOfLongestSubstring(string s) {
34         if(s.length()<=1)return s.length();
35         int start=0,maxsub=0;
36         int ASCIINUM=256;
37         int lastlocation[ASCIINUM];
38         fill(lastlocation,lastlocation+ASCIINUM,-1);
39         for(int i=0;i<s.size();i++)
40         {
41             if(lastlocation[s[i]-' ']>=start)
42             {
43                 maxsub=max(i-start,maxsub);
44                 start=lastlocation[s[i]-' ']+1;
45             }
46             lastlocation[s[i]-' ']=i;
47         }
48         return max((int)s.size() - start, maxsub);
49     }
50 };
51 ```

 

posted @ 2016-09-07 17:14  zeroArn  阅读(139)  评论(0)    收藏  举报