Longest Substring without repeating characters
Given A string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "ABCABCBB" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.
Problem Solving Ideas:
1, the most intuitive idea, each scan of a character, and the previous last not repeat after the character comparison, until the same character encountered. It is time to record the position of the last non-repeating character.
Class Solution {public: int lengthoflongestsubstring (string s) { int maxlen = 0; int norepeatstart = 0; int len=s.length (); for (int i=0; i<len; i++) { char EndChar = s[i]; char Localmaxlen = 1; for (int j=i-1; j>=norepeatstart; j--) { if (S[j]==endchar) { norepeatstart=j+1; break; } localmaxlen++; } if (Localmaxlen>maxlen) { maxlen=localmaxlen; } } return maxlen;} ;
2, the above code, the time complexity of the worst case is O (n^2), obviously not, we can use a hash table to record the last occurrence of each character position. Here is the code.
Class Solution {public: int lengthoflongestsubstring (string s) { int maxlen = 0; int norepeatstart = 0; int localmaxlen = 0; int len=s.length (); Map<char, int> Chartoindex; The position where a character has recently appeared for (int i=0; i<len; i++) { Map<char, Int>::iterator it=chartoindex.find (S[i]); if (It==chartoindex.end () | | | It->second<norepeatstart) { localmaxlen++; if (Localmaxlen>maxlen) { maxlen=localmaxlen; } } else{ norepeatstart=it->second+1; localmaxlen=i-it->second; } chartoindex[s[i]]=i; } return maxlen;} ;
3, however, the 2 method runs on the Leetcode is still very slow, even time is greater than the 1 method. There must be something wrong with it. In fact, the value range of char is up to 256, you can use an array to record the last occurrence of each character, thus eliminating the lookup cost of the map. This is a good idea. Here's the code:
Class Solution {public: int lengthoflongestsubstring (string s) { int maxlen = 0; int norepeatstart = 0; int localmaxlen = 0; int len=s.length (); int chartoindex[256]; Char has only 256 memset (Chartoindex,-1, 256*sizeof (int)); for (int i=0; i<len; i++) { if (chartoindex[s[i]]<norepeatstart) { localmaxlen++; if (Localmaxlen>maxlen) { maxlen=localmaxlen; } } else{ norepeatstart=chartoindex[s[i]]+1; Localmaxlen=i-chartoindex[s[i]]; } chartoindex[s[i]]=i; } return maxlen;} ;
[Leetcode] Longest Substring without repeating characters