Longest Substring without repeating characters
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.
Find the longest string of different substrings
Null length is 0 direct return 0
Length of 1, return 1
For cases greater than 1
To traverse a string:
Define a HashSet collection
For each element in the string, if it does not exist in the collection, join the collection
If it already exists in the collection: Assuming that this element is CH, to remove all elements that precede the set CH, left plus a
while (S.charat (left)! =ch) { set.remove (S.charat (left)); left + +; } // End While left++;
That's the main procedure.
All Programs
Public classSolution { Public intlengthoflongestsubstring (String s) {HashSet set=NewHashSet (); intleft = 0; intright = 0; intMax = 0; Charch; if(s==NULL&& s.length () ==0)return0; if(S.length () ==1)return1; for(Right=0;right<s.length (); right++) {ch=S.charat (right); if(Set.contains (ch)) {Max=math.max (max,right-Left ); while(S.charat (left)! =ch) {Set.remove (S.charat (left)); Left++; }//End Whileleft++; }Else{set.add (ch); // Right}//End If}//End formax = Math.max (max,right-Left ); returnMax; }//End}
Python program, not read
classsolution (object):deflengthoflongestsubstring (self, s):""": Type S:str:rtype:int""" ifLen (s) ==0:return0ifLen (s) ==1:return1Lastapppos={s[0]:0}#Last appear position of AlphabetLongestendinghere=[1]*len (s)#longest substring ending here forIndexinchXrange (1, Len (s)): Lastpos= Lastapppos.get (s[index],-1) ifLastpos<index-longestendinghere[index-1]: Longestendinghere[index]= Longestendinghere[index-1] + 1Else: Longestendinghere[index]= Index-Lastpos Lastapppos[s[index]]=IndexreturnMax (Longestendinghere)
Leetcode-longest Substring without repeating characters