https://leetcode.com/problems/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.
1 Public classSolution {2 Public Static intlengthoflongestsubstring (String s) {3 intMax=0;4 intFlag=0;5 intTemplen=0;6Map<character,integer> map=NewHashMap ();7 intstrlen=s.length ();8 for(inti=0;i<strlen;i++){9 CharC=S.charat (i);Ten if(Map.containskey (c)) { One intindex=Map.get (c); A if(Flag<=index) {templen=i-index;flag=index;} - Elsetemplen++; - } the Elsetemplen++; - Map.put (c,i); -max=Math.max (Max,templen); - //for (int j=0;j<=index;j++) { + //if (Map.containsvalue (j)) - //Map.Remove (S.charat (j)); Inserting a repeating key will update the value so that no duplicate elements are removed + // } A } at returnMax; - } - Public Static voidMain (String[]args) { -String s= "Tmmzuxt"; - System.out.println (lengthoflongestsubstring (s)); - } in}
Time-Out Program:
1 ImportJava.util.HashMap;2 ImportJava.util.Map;3 4 Public classSolution {5 Public Static intlengthoflongestsubstring (String s) {6 intMax=0;7Map<character,integer> map=NewHashMap ();8 intstrlen=s.length ();9 for(inti=0;i<strlen;i++){Ten CharC=S.charat (i); One if(!map.containskey (c)) {Map.put (c, i);}// A Else{ -max=Math.max (Max,map.size ()); - intindex=Map.get (c); the for(intj=0;j<=index;j++){ - if(Map.containsvalue (j)) - Map.Remove (S.charat (j)); - } + Map.put (c,i); - } + } A if(!map.isempty ()) max=Math.max (Max,map.size ()); at returnMax; - } - Public Static voidMain (String[]args) { -String s= "Bpfbhmipx"; - System.out.println (lengthoflongestsubstring (s)); - } in}
The reason is that many more unwanted remove operations
Longest Substring without repeating characters