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.
Analysis: This topic and Minimum Substring window has the similarities, two topics are to find a special window length, Minimum Substring Window is a string containing all the characters of a minimum window, The problem is to ask for a maximum window of all characters, both of which can be solved by two pointers methods.
The two key points of this question: (1) How to extend window (2) How to narrow the window when it encounters repeating characters.
We can use an array to hold the index of the character that has already appeared, or 1 if the character does not appear, and when a repeating character is encountered, we simply move the pointer to the beginning of the window to the position where the first repeating character appears.
Time complexity is O (n), Spatial complexity O (1). The code is as follows:
classSolution { Public: intLengthoflongestsubstring (strings) {intn =s.length (); if(n = =0)return 0; Vector<int> pos ( the, -1); intWin_start =0, Max_width =0; for(intWin_end =0; Win_end < n; win_end++){ if(Pos[s[win_end]] = =-1){//Not repeating characterPos[s[win_end]] =Win_end; Max_width= Max (max_width, Win_end-win_start +1); }Else{//repeating character for(; Win_start < pos[s[win_end]; win_start++) {//eliminate characters from Win_start to Pos[s[win_end]]Pos[s[win_start]] =-1; } Win_start++; Pos[s[win_end]]=Win_end; } } returnMax_width; }};
Leetcode:longest Substring without repeating characters