- Use a hash table to hold the position where the character appears;
- Use left and right to represent the leftmost and leftmost characters of the substring, respectively;
- Iterates through a string, if the current character is in a hash table and the current character is greater than left in the SID, indicating that there is the same character as the right index between left and right, at which point it is set to the value of the current value in the hash table;
- The current index value of +1, which is the number of characters, to find the current maximum length;
- Repeat 3-4 steps until the traversal is complete;
Feel this is a dynamic planning problem, temporarily useless dynamic planning analysis, and further.
classSolution (Object):defLengthoflongestsubstring ( Self, s):""": Type S:str: Rtype:int """Hashes={} left, right, length= 0,0,Len(s) max_len= 0 whileRight<LengthifHashes.get (S[right]) andHashes[s[right]]>=Left:left=Hashes[s[right]] [Hashes[s[right]]=Right+ 1Max_len= Max(Max_len, right-Left+ 1) Right+= 1 returnMax_len
Python solution Leetcode:3. Longest Substring without repeating characters