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.
思路一:
用一个HashMap存储字符串中各个字符在字符串中的位置,用start存储当前判断子串的起始位置。
从头至尾扫描各个字符(ch),当ch已经在Map中并且最近保存的位置信息在当前判断子串中(map.containsKey(ch) && map.get(ch)>=start),便将start值置为ch后一个字符的位置,然后将ch与其位置put进Map,更新最大长度。
1 public int lengthOfLongestSubstring(String s) { 2 if(s == null) { 3 return 0; 4 } 5 int max = 0; 6 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 7 int len = s.length(); 8 int start = 0; 9 for(int i=0; i<len; i++) { 10 char ch = s.charAt(i); 11 if(map.containsKey(ch) && map.get(ch)>=start) { 12 //当map.get(ch)<start时,ch已经不在当前判断的子串中了 13 start = map.get(ch) + 1; 14 } 15 map.put(ch, i); 16 max = Math.max(max, i - start + 1); 17 } 18 return max; 19 }
思路二:
假定字符串中所有的字符都是ASCII码,则可以使用长度为128的数组代替思路一中的Map。
1 public int lengthOfLongestSubstringII(String s) { 2 if(s == null) { 3 return 0; 4 } 5 int max = 0; 6 int[] lastIndex = new int[128]; 7 for(int i=0; i<128; i++) { 8 lastIndex[i] = -1; 9 } 10 int len = s.length(); 11 int start = 0; 12 for(int i=0; i<len; i++) { 13 char ch = s.charAt(i); 14 if(lastIndex[ch]>=start) { 15 start = lastIndex[ch] + 1; 16 } 17 lastIndex[ch] = i; 18 max = Math.max(max, i - start + 1); 19 } 20 return max; 21 }