从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。
可以减少时间, 但时间复杂度没有变O(n2)
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(s == null) 6 return 0; 7 char[] mychar = s.toCharArray(); 8 HashMap<Character, Integer> table = new HashMap<Character, Integer>(); 9 int result = 0; 10 for(int i=0; i<mychar.length; i++) 11 { 12 if(table.containsKey(mychar[i])) 13 { 14 result = table.size() > result? table.size():result; 15 i = table.get(mychar[i]); 16 table.clear(); 17 } 18 else 19 table.put(mychar[i], i); 20 } 21 result = table.size() > result? table.size():result; 22 return result; 23 } 24 }