用left、right两个指针(用的是数字,当成指针来理解)在String上移动。
每次迭代判定right指向的字符ch是否存在于HashMap中:
如果不存在,把这个字符作为key,位置作为值加入HashMap,right向右移动一格,尝试更新最大长度max;
如果存在,用ch作为key找到已存在字符的位置i,把left一步一步移动到i+1位置,途径的元素从HashMap删掉。
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0, left = 0, right = 0;
HashMap<Character,Integer> map = new HashMap<Character,Integer>(s.length());
while(right < s.length()) {
char ch = s.charAt(right);
if(!map.containsKey(ch)) {
map.put(ch,right);
++right;
ans = Math.max(ans, map.size());
}else {
int index = map.get(ch);
while(left < index+1) {
map.remove(s.charAt(left));
++left;
}
//此时left == map.get(ch)+1;
map.remove(ch);
}
}
return ans;
}
}
但是这样太慢,想了一下,HashSet就够了。
每次判断一下right指向的字符是否存在于HashSet中,相应地把left或right向左移动,宏观上看同样是左右指针只在数组上走一遍。
修改后时间减少了10ms这样。
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0, left = 0, right = 0;
HashSet<Character> table = new HashSet<Character>();
while(right < s.length()) {
if(!table.contains(s.charAt(right))) {
table.add(s.charAt(right));
++right;
ans = Math.max(ans, table.size());
}else {
table.remove(s.charAt(left));
++left;
}
}
return ans;
}
}