Brush Leetcode, see an algorithm, to the great God kneeling .... Read for a while to understand, the following talk about understanding
int lengthoflongestsubstring (string s) {int locs[256];//stores the last occurrence of characters that have occurred int max = 0;//length int currenthead = -1;// Initial computed length of the head memset (locs,-1, sizeof (locs)); for (int i = 0; i < s.size (); i++)//somewhat difficult to think, the following system explains {if (Locs[s[i]] > Currenthea D) {currenthead = Locs[s[i]];} if (I-currenthead > Max) {max = I-currenthead;} Locs[s[i]] = i;} return Max;}
The simplest idea of this problem is the two-layer traversal:
1. The first layer iterates through all the characters, representing the substring beginning with the character of each position;
2, the second layer, the beginning of a position character, backward traversal, you can use the Map container insert operation to determine whether there are duplicate characters, and calculate the length;
3, in doing so, it is actually to find the string of all the non-repeating characters of the substring, get the maximum length, the time complexity of O (N2).
But you can see that the second layer of traversal and the first layer is coincident, and thus can be combined to the first layer of traversal, the method is to use an additional array to hold the character position information, the specific idea is as follows:
1, two-layer traversal, the second layer traversal to the current beginning of a string of characters, the second traversal stop, the first layer of traversal can jump directly to the first occurrence of the repetition of the position to start the loop, Because a substring between the head character and the character of the repeating character as the first character, it is not possible to skip the repeating character and the length must be lower than the current header string.
2, only with a layer of traversal, and constantly update the storage characters appear in the previous position, so that the equivalent of jumping.
Give me a chestnut, abccabc:
Two-level traversal, there will be abc,bc,c,cab,abc and so on, using the above algorithm, will only calculate the ABC,CAB,ABC substring (rough expression of the difference, the specific location of the subscript value should be handled carefully).
This algorithm is formed on the basis of a deep understanding of the characteristics of cyclic and character string problems, and can be extended to many similar two-layer loops with coincident parts; another, to reduce the complexity of time, we have to increase the complexity of space.
Longest Substring without repeating characters