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.
Public classSolution { Public intlengthoflongestsubstring (String s) {//use HashMap to cycle through only once. //use start and I two pointers to maintain the substring, using a hash table to record the characters appearing in the string. Each loop I moves 1 bits to the right, then I determine whether the character I pointed to after I shifted right has appeared in the hash table: If it has occurred, it indicates that a repeating character appears, records the length of the substring and compares it with the longest length, and then deletes the character before the repeating letter in the substring and updates start; It indicates that there are no repeating characters and that the character is placed in the hash table. /*time complexity O (n); Space complexity O (m), m depends on the length of the non-repeating substring*/HashMap<Character,Integer> map=NewHashmap<character,integer>(); intLen=0; intRes=0; intStart=0; intI=0; for(I=0;i<s.length (); i++){ if(!Map.containskey (S.charat (i))) {Map.put (S.charat (i), i); /*len=i-start+1; Res=math.max (len,res);*/ }Else{len=i-start; Res=Math.max (len,res); intt=Map.get (S.charat (i)); for(intj=start;j<=t;j++) {Map.Remove (S.charat (j)); } Start=t+1; Map.put (S.charat (i), i); } } returnMath.max (res,i-start); //return res; }}
Longest Substring without repeating characters