滑动窗口,hashset判断是否有重复字符
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<Character>();
int left = 0;
int max = 0;
for(int i = 0; i < s.length();i++){
if(!set.contains(s.charAt(i))){
set.add(s.charAt(i));
max = Math.max(set.size(),max);
}else{
for(int j = left; j < i; j++){
set.remove(s.charAt(j));
if(s.charAt(j)==s.charAt(i)){
left = j+1;
//set不能存储重复字符,所以等去除后在加入
set.add(s.charAt(i));
break;
}
}
}
}
return max;
}
}
1. set不能存储重复字符
右指针往右移,判断有无重复字符,若无,则入set,字符串长度+1;若有,入set,移动左指针,直到左右指针之间的字符串没有重复字符,然后再继续移动右指针。
2.什么时候判断字符串的长度,右指针往右移动时