public static int lengthOfLongestSubstring(String s) {
int ans=0;
int l=0;//左指针
int r=0;//右指针
Set<Character> set=new HashSet<>();//记录出现的字符
//模拟队列
while (r<s.length()){
if(!set.contains(s.charAt(r))){
set.add(s.charAt(r));//当下一个字符不重复,加入队列
r++;
}else {
//当下一个字符已有,不断删除前面的字符直到遇到该字符
while (s.charAt(l)!=s.charAt(r)){
set.remove(s.charAt(l));
l++;
}
set.remove(s.charAt(l));//删除重复字符
set.add(s.charAt(r));//下一个字符加入
l++;
r++;
}
ans=Math.max(ans,set.size());//更新答案
}
return ans;
}
滑动窗口算法leetcode.3
最新推荐文章于 2024-07-23 17:36:37 发布