Given a string, find the length of the oldest string that does not contain repeating characters.
Example 1:
Input : "ABCABCBB"
Output : 3
Explanation : The oldest string of non-repeating characters is "abc", with a length of 3.
Example 2:
Input : "BBBBB"
Output : 1
Main idea: "Sliding window", using a container to save the traversed characters.
Iterates through the string, saves the characters that are not duplicated in the window, adds one to the right edge of the window, and then slides one bit to the right, reducing the window size from the left edge of the window when repeating characters are encountered, until that repeating character is not included in the container. In essence, it also uses external space.
Solution 1:
intLengthoflongestsubstring (strings) { intn =s.size (); Unordered_set<Char>Set; intMax =0, i =0, j =0; while(I < n && J <N) {Auto F=Set. Find (S.at (j)); if(f = =Set. End ()) { //right Border swipe right one Set. Emplace (S.at (j + +)); Max= Std::max (max, J-i); } Else { //left Border narrows right one Set. Erase (S.at (i++)); } } returnMax;}
Solution 2:
intLengthoflongestsubstring (strings) {intn =s.size (); Unordered_map<Char,int>MP; intMax =0; for(intj =0, i =0; J < N; ++j) {if(Mp.count (s.at (j)) >0) { //The next one that shrinks the left side of the window to duplicate characters directlyi =Std::max (mp.at (s.at (j)), I); } Max= Std::max (max, J-i +1); //right Border swipe right oneMp.emplace (S.at (j), J +1); } returnMax; }
3: Longest string with no repeating characters