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.
began to use the exhaustive method, all the substrings are traversed out, the result is timed out.
1 Public classSolution {2 Public intlengthoflongestsubstring (String s) {3 if(s.length () = = 0){4 return0;5 }6 if(s.length () = = 1)7 return1;8 intresult = 1;9 for(inti = 0; I < s.length ()-result; i++){Ten intj = i + 1; One for(; J < S.length (); j + +){ AString Sub =s.substring (i, j); - if(-1 = =Sub.indexof (S.charat (j))) - { the if(Sub.length () + 1 >result) -result = Sub.length () + 1; - Continue; - } + Break; - } + } A at returnresult; - } -}
Referring to others, only traversing the string once, using the hash table to record the location of S.charat (i). Constantly updated result, a bit greedy algorithm feel, each time the current string to record the starting position
Reference connection I'm too lazy to find it.
Importjava.util.Hashtable; Public classSolution { Public intlengthoflongestsubstring (String s) {if(s.length () = = 0){ return0; } if(s.length () = = 1) return1; intresult = 0;//The result of the last return intindex =-1;//the previous position of the current substring start positionHashtable<character, integer> map =NewHashtable<character, integer> ();//S[i] where it appears for(inti = 0; I < s.length (); i++) {Integer position=Map.get (S.charat (i)); if(NULL! = Position && position >index) Index=position; if(I-index >result) Result= i-index; Map.put (S.charat (i), i); } returnresult; }}
Longest Substring without repeating characters