In the string, the longest continuous substring is not repeated.
Idea: Use HashMap, find unordered_map faster than map, set a starting position, calculate the length, to reduce the value of the starting position
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
When C appears again, the start value is set to Map[c]+1=3, and for the next B, because Map[b]<start, the direct map[b]=i
1 classSolution {2 Public:3 intLengthoflongestsubstring (strings) {4unordered_map<Char,int>Mymap;5 intflag=0;6 intstart=0, i=0;7unordered_map<Char,int>:: iterator ite;8 while(i<s.size ()) {9Ite=Mymap.find (S[i]);Ten if(ite==Mymap.end ()) { Onemymap[s[i]]=i; AFlag=max (flag,i-start+1); - } - Else{ the if(mymap[s[i]]>=start) -start=mymap[s[i]]+1; -mymap[s[i]]=i; -Flag=max (flag,i-start+1); + } -++i; + } A returnFlag; at } -};
Time complexity: O (N)
Time-Out Solution:
1 classSolution {2 Public:3 intLengthoflongestsubstring (strings) {4map<Char,int>Mymap;5 intI=0, max=0, Flag;6map<Char,int>:: iterator ite;7 while(i<s.length ()) {8Ite=Mymap.find (S[i]);9 if(ite==Mymap.end ()) {Tenmymap[s[i]]=i; One if(Mymap.size () >max) Amax=mymap.size (); - } - Else{ theFlag=ite->second; - mymap.clear (); Every time it clears, it's the way it fails. - for(intj=flag+1; j<=i;++j) { -mymap[s[j]]=J; + } - } +++i; A } at returnMax; - } -};
3 longest Substring without repeating characters (longest non-repeating contiguous substring medium)