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 solution of the string s is scanned only once, that is, the time complexity is O (n), the code is as follows:
Public classSolution { Public intlengthoflongestsubstring (String s) {intStart = 0; Map<Character,Integer> map =NewHashmap<character,integer>(); intMax_length = 0; intSize = S.length ();//string Length for(inti=0;i<size;i++) { Charc =S.charat (i); if(Map.containskey (c)) {intSub_length = istart; Max_length= Sub_length>max_length?sub_length:max_length; intindex = Map.get (S.charat (i));//the position of C has occurred before//Remove start to index all characters from map for(intj=start;j<=index;j++) {Map.Remove (S.charat (j)); } map.put (C,i); Start= index+1;//Update Start } Else{map.put (c,i); if(i==size-1) Max_length = Map.size () >max_length?map.size (): max_length; } } returnmax_length; }}
The question is how to determine whether the current character has occurred in a string in a constant time, and a hashmap must be used. Using the Contains method of the string directly results in inefficient, limit time exceed.
Longest Substring without repeating characters