Poison

424. Longest Repeating Character Replacement

Sliding Window
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
26
27
28
29
30
31
32
class Solution {
public int characterReplacement(String s, int k) {
// window: [i, j]
int[] windowMap = new int[26];

int maxLength = 0;

int i = 0;
for (int j = 0; j < s.length(); j++) {
windowMap[s.charAt(j) - 'A']++;
// 移除元素直到 window 满足条件
while (windowIllegal(windowMap, k)) {
windowMap[s.charAt(i) - 'A']--;
i++;
}

maxLength = Math.max(maxLength, j - i + 1);
}

return maxLength;
}

private boolean windowIllegal(int[] windowMap, int k) {
int charCount = 0, mostCharCount = 0;
for (int count : windowMap) {
charCount += count;
mostCharCount = Math.max(mostCharCount, count);
}

return charCount - mostCharCount > k;
}
}
Sliding Window
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int characterReplacement(String s, int k) {
// window: [i, j]
int[] windowMap = new int[26];

int mostCharCount = 0, maxLength = 0;

int i = 0;
for (int j = 0; j < s.length(); j++) {
windowMap[s.charAt(j) - 'A']++;
mostCharCount = Math.max(mostCharCount, windowMap[s.charAt(j) - 'A']);

if (j - i + 1 > mostCharCount + k) {
windowMap[s.charAt(i) - 'A']--;
i++;
}

maxLength = Math.max(maxLength, j - i + 1);
}

return maxLength;
}
}
Reference

424. Longest Repeating Character Replacement