【题解】力扣424. 替换后的最长重复字符
题目来源:424. 替换后的最长重复字符
思想及算法:
双指针,滑动窗口
一个左指针记录窗口开始位置,一个右指针记录窗口结束位置。
需要一个数组,用来维护窗口内字母出现的次数。
需要一个变量来记录历史最长重复字符
主要是计算窗口中字符串出现次数最多的字母个数+K是否满足条件。
- 窗口扩张:left不变,right++
- 窗口滑动:left++,right++
historyCharMax 保存滑动窗口内相同字母出现次数的 历史 最大值,通过判断窗口宽度 (right - left + 1)(right−left+1) 是否大于 historyCharMax + KhistoryCharMax+K 来决定窗口是否做滑动,否则窗口就扩张。
时间复杂度为O(N)
class Solution {
public int characterReplacement(String s, int k) {
char[] chars = s.toCharArray(); // 字符串改为字符数组
int[] map = new int[26]; // 记录26个字母出现的次数
int left = 0;
int right = 0;
int historyStr = 0; // 记录历史字符串的最大值
for (right = 0; right < chars.length; right++) {
int index = chars[right] - 'A';
map[index]++;
historyStr = Math.max(historyStr, map[index]);
if (right - left + 1 > historyStr + k) { // 如果窗口长度大于出现字母历史最大值加k
map[chars[left] - 'A']--;
left++; // 窗口滑动,不扩张
}
}
return right - left;
}
}