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" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
1 public class Solution { 2 public static int lengthOfLongestSubstring(String s) { 3 int max=0; 4 int flag=0; 5 int templen=0; 6 Map<Character,Integer> map=new HashMap(); 7 int strlen=s.length(); 8 for(int i=0;i<strlen;i++){ 9 char c=s.charAt(i); 10 if(map.containsKey(c)){ 11 int index=map.get(c); 12 if(flag<=index){templen=i-index;flag=index;} 13 else templen++; 14 } 15 else templen++; 16 map.put(c,i); 17 max=Math.max(max,templen); 18 // for(int j=0;j<=index;j++){ 19 // if(map.containsValue(j)) 20 // map.remove(s.charAt(j));插入重复键,将会更新值,所以不用去除重复元素 21 // } 22 } 23 return max; 24 } 25 public static void main(String[]args){ 26 String s="tmmzuxt"; 27 System.out.println(lengthOfLongestSubstring(s)); 28 } 29 }
超时的程序:
1 import java.util.HashMap; 2 import java.util.Map; 3 4 public class Solution { 5 public static int lengthOfLongestSubstring(String s) { 6 int max=0; 7 Map<Character,Integer> map=new HashMap(); 8 int strlen=s.length(); 9 for(int i=0;i<strlen;i++){ 10 char c=s.charAt(i); 11 if(!map.containsKey(c)){ map.put(c, i);}// 12 else{ 13 max=Math.max(max,map.size()); 14 int index=map.get(c); 15 for(int j=0;j<=index;j++){ 16 if(map.containsValue(j)) 17 map.remove(s.charAt(j)); 18 } 19 map.put(c,i); 20 } 21 } 22 if(!map.isEmpty()) max=Math.max(max,map.size()); 23 return max; 24 } 25 public static void main(String[]args){ 26 String s="bpfbhmipx"; 27 System.out.println(lengthOfLongestSubstring(s)); 28 } 29 }
原因是多了很多不需要的remove操作