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 maximum length of the non-repeating substring in a string is a classical greedy method to solve the problem (the substring is naturally continuous, and the subsequence does not require continuous).
1 Public classSolution {2 Public intlengthoflongestsubstring (String s) {3 if(s==NULL&& s.length () ==0)4 return0;5Hashset<character> set =NewHashset<character>();6 intMax = 0;7 intWalker = 0;8 intRunner = 0;9 while(runner<s.length ())Ten { One if(Set.contains (S.charat (runner))) A { - if(max<runner-Walker) - { themax = runner-Walker; - } - while(S.charat Walker)! =S.charat (runner)) - { + Set.remove (S.charat (Walker)); -walker++; + } Awalker++; at } - Else - { - Set.add (S.charat (runner)); - } -runner++; in } -max = Math.max (max,runner-Walker); to returnMax; + } -}
Algorithm complexity O (n), spatial complexity O (n).
Another kind of C + + is more concise
1 classSolution {2 Public:3 intLengthoflongestsubstring (strings) {4unordered_map<Char,int> um;//where each character last appears during a UM record traversal5 intres=0, i=0, j=0;//J Record the starting point of the current non-repeating substring, I record the end point of the currently distinct substring6 7 while(I<s.size ()) {//Traversing Strings8 if(Um.find (S[i])!=um.end () && um[s[i]]>=j)//if S[i is present in the currently maintained non-repeating substring]9j=um[s[i]]+1;//Update JTen Else //if S[i is not present in the currently maintained non-repeating substring] OneRes=max (res,i-j+1);//Update the results, take the larger person A -Um[s[i]]=i;//Update um -i++; the } - returnRes; - } -};
Algorithm time complexity O (n), Spatial complexity O (1). Because the number of ASCLL code characters 128, here with Unorder_map to record each character in the last occurrence of the string in the position, the space consumption of unordered_map maximum of 128, so the time complexity is a constant number of levels. The time complexity of the UNORDERED_MAP lookup insert operation is O (1), so the time of the entire algorithm is O (n).
Leetcode 3--longest Substring without repeating characters