class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int res = 0;
int end=0,start=0;
Set<Character> set=new HashSet<>();
while(start<n && end<n){
if(set.contains(s.charAt(end))){
set.remove(s.charAt(start++));
}else{
set.add(s.charAt(end++));
res=Math.max(res,end-start);
}
}
return res;
}
}
滑动窗口法:
定义两个指针,start和end,代表当前窗口的开始和结束位置,同样使用hashset,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值