滑动窗口(sliding window),以424为例

分析
本题是一个典型的使用滑动窗口思想的问题。
- 滑动过程中,得到该窗口内的字符数量最多的值max, 如果窗口长度length - max 小于给定的替换长度k, 那么此时满足条件,可以继续拉大滑动窗口,右窗口往前走。反之,左窗口往前走,即缩小窗口。
- 值得注意的是,如果缩小窗口,max值可能会发生变化,需要判断max是否是最左边的窗口的字符的数量,是则max - 1,否则不变。
- 左窗口向右滑动,最左边的字符数量需要减去1.
代码
public int characterReplacement(String s, int k) {
int[] letters = new int[26];
int left = 0; int right = 0; int max = 0;int ans = 0;
while(right < s.length()) {
letters[s.charAt(right) - 'A'] += 1;
max = Math.max(max, letters[s.charAt(right) - 'A']);
if(right - left + 1 - max > k) {
if(max == letters[s.charAt(left) - 'A']) {
max -= 1;
}
letters[s.charAt(left) - 'A'] -= 1;
left += 1;
}
ans = Math.max(ans, right - left + 1);
right += 1;
}
return ans;
}
总结
滑动窗口思想很重要,与回溯(递归), 动态规划一样,对于字符串类型的问题,往往能大大降低复杂度。