title: given a string of strings, find the oldest string with no repeating characters in string.
Example:
Given "abcabcbb"
, the answer "abc"
is, which the length is 3.
Given "bbbbb"
, the answer "b"
is, with the length of 1.
Given "pwwkew"
, the answer "wke"
is, with the length of 3. Note that the answer must was asubstring, is "pwke"
a subsequence and not a substring.
Ideas:
First, because we are looking for a non-repeating substring, we use the hashset structure to hold the characters that have been found, and the hashset holds all the characters from the pre to another position I in the middle.
Traverse the given string s from the beginning, each traversing one, to determine if there is a character in the hashset, assuming that it is traversed at the I position:
1: If not, the character is added to the HashSet, indicating that the length of the substring is increased by one, that is, the prev~i position of the string is no repeating character, update the length of the longest string max_str;
2: If there is, start looping through the prev position until the character that is equal to the I position character is found, and then prev points to the position of the character position +1, I continues the traversal.
Until I==len ends the traversal. However, the size of Max (I-prev, MAX_STR) should be computed at this time, the size of the MAX_STR is updated, and the final max_str is returned;
Extended:
Suppose the subject asks to find the oldest string without duplication, you need to use two variables to save the left and right position of the window, whenever the MAX_STR update, you need to update the window left and right position. Finally, use s.substring (left, right) to get the oldest string.
The code:
1 Public classSolution {2 Public intlengthoflongestsubstring (String s) {3 if(s = =NULL|| S.length () < 1)4 return0;5Hashset<character> set =NewHashset<character>();6 intPre = 0;//left edge of window7 intMax_str = Integer.min_value;//Longest string length8 inti = 0;//the right edge of the window9 intLen =s.length ();Ten while(I <len) One { A if(Set.contains (S.charat (i)))//find the character that is equal to the I position, the pre points to the next position of the character, and restarts the window - { - if(I-pre >max_str) theMax_str = i-Pre; - while(S.charat (PRE)! = S.charat (i))//until you find the character that is equal to the current character, then you can start the new round of window counting again - { - Set.remove (S.charat (pre)); +Pre + +; - } +Pre + +; A } at Else - { - Set.add (S.charat (i)); - } -i++; - } inMax_str = Math.max (Max_str, I-pre);//I go backwards until the length of S is exceeded, and the size of the window is calculated at this time - returnMax_str; to + } -}
Leetcode3---> Oldest string length with no repeating characters