剑指offer 48. 最长不含重复字符的子字符串
题目描述
解题思路
滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
//窗口的左右边界,左闭右开[left, right),这样窗口大小就是right - left
int left = 0, right = 0;
//统计窗口内各字符出现的次数
Map<Character, Integer> cnt = new HashMap<>();
int res = 0;
while (right < s.length()) {
char intoWindow = s.charAt(right);
right++;
cnt.put(intoWindow, cnt.getOrDefault(intoWindow, 0) + 1);
while (cnt.get(intoWindow) > 1) {
char outOfWindow = s.charAt(left);
left++;
cnt.put(outOfWindow, cnt.getOrDefault(outOfWindow, 0) - 1);
}
res = Math.max(res, right - left);
}
return res;
}
}