题目链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked
滑动窗口
左边界遍历字符串,右边界每次判断
class Solution {
public int lengthOfLongestSubstring(String s) {
//存储字符串长度
int n = s.length();
//定义一个哈希集合,判断是否有重复的字符
Set<Character> set = new HashSet<Character>();
//右边界
int right = -1;
//存储答案
int ans = 0;
//左边界遍历字符串
for(int left = 0; left < n; left++){
//左边界每次向右移动一格时,移除一个字符
if(left != 0){
set.remove(s.charAt(left - 1));
}
//当下一个字符不重复且在范围内时,右边界向右扩展
while(right + 1 < n && !set.contains(s.charAt(right + 1))){
set.add(s.charAt(right + 1));
right++;
}
//更新答案
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
还剩92题!