Test instructions: Gives a string that asks for the length of a substring, which satisfies all characters without repetition. Characters may contain punctuation, not just letters. According to the ASCII code, there is a 2^8=128.
Idea: Sweep each character from left to right, judging how far the character is from the last occurrence, and updating max if it is larger than Max. If it is less than, it is not updated. Each sweep to a character needs to update his presence. There is also a point of note in this, for example:
If there is a length of 16 strings s= "aRbtbqwecpoiuyca"
When sweep to 2nd B, the distance from the previous B is 2; (direct minus)
When sweeping to 2nd C, the distance from the previous C is 6; (direct minus)
But! When sweep to 2nd a, the distance from the previous a is 15, but there are already B and C in this string are duplicated, is not consistent. True length = position of 2nd A-1th position of C.
Suppose the current sweep of the character is ' A ', in fact the length of the formula should be this: Len = I-max (Cur,pos[a])
Here cur refers to the position of a character, the character is the nearest to a distance a, and between the character and a will also appear the character once, (that is, between two A, if there are two occurrences of the character, record the position of the 1th character, if more than one occurrence, Record the position of the character at the 2nd occurrence of the right number) the value of this cur is updated at any time.
Note: Pit! The complexity of this algorithm is completely o (n), which is really powerful. Think for 2 days, I originally thought to do with hash, feel a bit of trouble, has been thinking more simple, the following code of others is really concise to no way, admire.
1 classSolution {2 Public:3 intLengthoflongestsubstring (strings) {4 //Start Typing your/C + + solution below5 //Do not write int main () function6 intlocs[ the];//Save the position of the last occurrence of the character7memset (locs,-1,sizeof(Locs));8 9 intIDX =-1, max =0;//IDX is the starting position of the current substring -1Ten for(inti =0; I < s.size (); i++) One { A if(Locs[s[i]] > IDX)//if the current character has occurred, the starting position of the current substring is the position of the last occurrence of the character +1 - { -IDX =Locs[s[i]]; the } - - if(I-idx >max) - { +max = i-idx; - } + ALocs[s[i]] =i; at } - returnMax; - } -};
longest Substring without repeating characters
The above code is copied over the word.
Leetcode longest Substring without repeating characters longest non-repeating substring