3 Longest Substring Without Repeating Characters(最长不重复连续子串Medium)
题目意思:求字符串中,最长不重复连续子串
思路:使用hashmap,发现unordered_map会比map快,设置一个起始位置,计算长度时,去减起始位置的值
eg:a,b,c,d,e,c,b,a,e
0 1 2 3 4
0 1 5 3 4
0 6 5 3 4
7 6 5 3 4
7 6 5 3 8
再次出现c时,将start值置为map[c]+1=3,对于下一个b,因为map[b]<start,则直接map[b]=i
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 unordered_map<char,int> mymap; 5 int flag=0; 6 int start=0,i=0; 7 unordered_map<char,int>::iterator ite; 8 while(i<s.size()){ 9 ite=mymap.find(s[i]); 10 if(ite==mymap.end()){ 11 mymap[s[i]]=i; 12 flag=max(flag,i-start+1); 13 } 14 else{ 15 if(mymap[s[i]]>=start) 16 start=mymap[s[i]]+1; 17 mymap[s[i]]=i; 18 flag=max(flag,i-start+1); 19 } 20 ++i; 21 } 22 return flag; 23 } 24 };
时间复杂度:O(n)
超时解法:
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 map<char,int> mymap; 5 int i=0,max=0,flag; 6 map<char,int>::iterator ite; 7 while(i<s.length()){ 8 ite=mymap.find(s[i]); 9 if(ite==mymap.end()){ 10 mymap[s[i]]=i; 11 if(mymap.size()>max) 12 max=mymap.size(); 13 } 14 else{ 15 flag=ite->second; 16 mymap.clear(); //每次清空,是及其失败的做法 17 for(int j=flag+1;j<=i;++j){ 18 mymap[s[j]]=j; 19 } 20 } 21 ++i; 22 } 23 return max; 24 } 25 };