滑动窗口
# 3. 无重复字符的最长子串 - 力扣(LeetCode) (opens new window)
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> window = new HashMap<>();
int left = 0, right = 0;
int res = 0;
while (right < s.length()) {
char c = s.charAt(right);
right++;
// 进行窗口内数据的一系列更新
window.put(c, window.getOrDefault(c,0) + 1);
// 判断左侧窗口是否要收缩
while (window.get(c) > 1) {
char d = s.charAt(left);
left++;
// 进行窗口内数据的一系列更新
window.put(d, window.getOrDefault(d,0) - 1);
}
// 在这里更新答案
res = Math.max(res, right -left);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# **拼多多:**最多允许一对相邻重复字符的最长子串问题
public class Solution {
public int longestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
int left = 0, maxLen = 1, repeatCount = 0;
for (int right = 1; right < s.length(); right++) {
// 检查当前字符与前一个是否重复
if (s.charAt(right) == s.charAt(right - 1)) {
repeatCount++;
}
// 若相邻重复次数超过1,移动左指针直到合法
while (repeatCount > 1) {
if (s.charAt(left) == s.charAt(left + 1)) {
repeatCount--;
}
left++;
}
// 更新最大长度
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2025/06/13, 00:51:28