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.
A solution to the problem
Because the topic gives a tag for Hashtable and two pointers
Therefore, we can define a hashtable, and two Pointers,index1 and Index2, first of all the elements in the string are constantly added, and if duplicates are found, then the duplicate elements and the elements before it are removed, Their position in the string is marked with Index1 and Index2, and the maximum size of Hashtable was found. The time complexity of this idea is the O (n) code as follows
1 Public classSolution {2 Static Public intlengthoflongestsubstring (String s) {3 Char[] Char1 =S.tochararray ();4 intLongestlength = 0;5 intStartIndex = 0;6 intLastIndex = 0;7Hashmap<character, integer> HashMap =NewHashmap<character, integer>();8 for(inti = 0; i < char1.length; i++) {9 if(Hashmap.containskey (Char1[i])) {TenLastIndex =Hashmap.get (Char1[i]); One if(Longestlength < (i-StartIndex)) { ALongestlength = i-StartIndex; - } - for(intj = StartIndex; J <= LastIndex; J + +) { the Hashmap.remove (Char1[j]); - } -StartIndex = lastindex+1; - } + Hashmap.put (Char1[i], i); - } + if(longestlength<char1.length-StartIndex) Alongestlength=char1.length-StartIndex; at returnlongestlength; - } -}
However, after the submission of time Limit exceeded, it seems that the complexity is still too high, the reason is that in the middle there are two for loops, the second for loop each time the deletion must traverse one side, so the time cost is necessarily very large.
Idea two:
In fact, after each addition, we do not have to delete the duplicate elements in the HashMap, we can use a pointer to record the location of the element to be deleted, if there is a duplicate element, the pointer is placed as the last occurrence of the repeating element position +1, Determine the length of the previous maximum substring and the size of the substring length produced by this time. This element is then added into the HashMap. Of course, it is also necessary to determine the length of the last substring obtained and the previous length comparison.
The Java code is as follows
public class Solution { static public int lengthoflongestsubstring (String s) {map<character, integer> HashMap = New Hashmap<character, integer> (); int length = 0;int pointer = 0;for (int i = 0; i < s.length (); i++) {if (Hashm Ap.containskey (S.charat (i)) && Hashmap.get (S.charat (i)) >= pointer) {length = Math.max (i-pointer, length); pointer = Hashmap.get (S.charat (i)) + 1;} Hashmap.put (S.charat (i), i); Return Math.max (s.length ()-pointer, length);}}
Java for Leetcode 003 longest Substring without repeating characters