滑动窗口 02

49 阅读1分钟

424. 替换后的最长重复字符.png

题解:

  • int[] memory 来记录当前窗口中字符的数量,后面随着窗口移动要更新
  • curMaxCount 记录当前窗口最多数量的字符的数量
  • 判断窗口是否向前滑动:窗口大小 > 最多字符数量 + 可替换数量,即:end - start + 1 > curMaxCount + k
class Solution {

    private int[] memory = new int[26]; // 记录窗口中字符的数量

    public int characterReplacement(String s, int k) {
        int start = 0, res = 0, curMaxCount = 0; // curMaxCount记录当前窗口中最多的字符数量
        int len = s.length();
        for (int end = 0; end < len; end++) {
            // 更新窗口最多字符数量,同时将新增加的尾部字母更新到记忆数组中,++放在前面,先添加到数组,再比较大小
            curMaxCount = Math.max(curMaxCount, ++memory[s.charAt(end) - 'A']);
            // 窗口内所有字符数量 > 最多字符数量 + k(可替换的数量) 就要将窗口前移了
            while (end - start + 1 > curMaxCount + k) {
                memory[s.charAt(start) - 'A']--;
                start++;
            }
            res = Math.max(res, end - start + 1);
        }
        return res;
    }

}