🌗 剑指 Offer 48. 最长不含重复字符的子字符串
2022年10月10日
- algorithm
🌗 剑指 Offer 48. 最长不含重复字符的子字符串
难度: 🌗
问题描述
解法
class Solution {
public int lengthOfLongestSubstring(String s) {
// 思路:
// 滑动窗口
int len = s.length();
if(len == 0) {
return 0;
}
int left = 0;
int right = 1;
HashSet<Character> set = new HashSet<>();
int res = 1;
set.add(s.charAt(0));
while(right < len) {
char c = s.charAt(right);
if(!set.contains(c)) {
res = Math.max(res, right - left + 1);
right ++;
set.add(c);
continue;
}
// 遇到重复字符,滑动左窗口
while(s.charAt(left) != c) {
char rm = s.charAt(left);
set.remove(rm);
left ++;
}
left ++;
res = Math.max(res, right - left + 1);
right ++;
}
return res;
}
}