思路:看到题目首先想到最大字符串匹配KMP算法
1 public static int lengthOfLongestSubstring(String s) { 2 int maxLength = 0; 3 StringBuilder sb = new StringBuilder(s); 4 a:for(int i = 0;i<sb.length();i++){ 5 StringBuilder sb2 = new StringBuilder(""); 6 sb2.append(sb.substring(i,i+1)); 7 b:for(int j=i+1;j<sb.length();j++){ 8 c:for(int k =0;k<sb2.length();k++){ 9 if(!sb.substring(j,j+1).equals(sb2.substring(k,k+1))){ 10 11 }else{ 12 if(maxLength<j-i) 13 maxLength = j-i; 14 break b; 15 } 16 if(k == sb2.length()) 17 sb2.append(sb.substring(j,j+1)); 18 } 19 } 20 } 21 return maxLength; 22 }
参考后代码
public static int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))){ i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; }