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.
The problem of finding the longest non-repeating substring is similar to the previous isomorphic Strings isomorphic string, and we are creating an integer array of 256-bit size instead of a hash table, because the ASCII tables are capable of representing 256 characters, so all the characters can be recorded. Then we need to define two variables, res and left, where Res is used to record the length of the longest no-repeat substring, where it points to the start of the leftmost substring, and then we traverse the entire string, for each character traversed, if the string in the hash table corresponds to a value of 0, The description did not encounter the character, then the longest non-repeating substring is calculated, I-left +1, where I is the longest non-repeating substring rightmost position, left is the leftmost position, there is also a case to calculate the longest non-repeating substring, that is, when the value in the hash table is less than left, This is because duplicate characters appear at this point, the left position is updated, and if new characters are encountered, the longest non-repeating substring will be recalculated. Finally, each time you assign the value of the current character to I+1 in the Hashtable. The code is as follows:
classSolution { Public: intLengthoflongestsubstring (strings) {intm[ the] = {0}, res =0, left =0; for(inti =0; I < s.size (); ++i) {if(M[s[i]] = =0|| M[s[i]] <Left ) {Res= Max (res, I-left +1); } Else{ Left=M[s[i]]; } M[s[i]]= i +1; } returnRes; }};
[Leetcode] Longest Substring without repeating characters longest non-repeating substring