Topic:
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.
Tag:
String; Hash Table; Pointers
Experience:
This problem is very difficult for me, read a lot of answers, or not very ... Now I just know a general meaning.
The general meaning is that first we have a map, where <key, Value>=<char, char is the last occurrence in string s >. It then begins by checking the char in the string one by one.
Assuming that string s = "cxyzabdECB", now our substring is "abd", then there are two cases where we can directly increase the length of the current substring, one is now the char is the first occurrence, (such as the emergence of E, Then it can become Abde); the other is that although this char appeared previously, it did not appear in the current substring, such as the C at the back of the Abde, judging by Map[s[i]] < I-curlen, It means that the previous C appeared outside the range of Abdec. In conclusion, the common feature of both cases is that char is not present in the current substring.
In addition to the above two cases, it is char in the present substring, then our substring can only retain this part of the later, that is, from the last time after this char to the current position. Example: Abdec Now the next check encountered B, in order to be able to add in the B, you can only reserve dec, become DECB.
1 classSolution {2 Public:3 intLengthoflongestsubstring (strings) {4 //Map<char, last index this char appears in the string5map<Char,int>indexes;6 //length of current substring7 intCurlen =0;8 //length of max substring length so far9 intMaxLen =0;Ten intn =s.length (); One A for(inti =0; I < n; i++) { - CharCH =S[i]; - //If this char appears the first time or the //Is isn't part of the substring - if((Indexes.count (s[i]) = =0) || -(Curlen < I-Indexes[s[i])) { -curlen++; +}Else { -Curlen = (I-Indexes[s[i]]); + } A //Update atIndexes[s[i]] =i; -MaxLen = (Curlen > MaxLen)?Curlen:maxlen; - } - returnMaxLen; - } -};
[Leetcode] Longest Substring without repeating characters (C + +)