var characterReplacement = function (s, k) {
let n = s.length;
let left = 0;
let right = 0;
let mapping = {};
let res = 0;
while (right < n) {
let c = s[right];
mapping[c] = (mapping[c] || 0) + 1;
right++; //扩大窗口
let maxCount = getMaxCount();
// 当前窗口长度 - 当前窗口出现的最多字符的次数 > 需要替换的字符数
// 当需要替换的字符数大于 k 时,才需要缩小窗口
while (right - left - maxCount > k) {
let c = s[left];
mapping[c]--;
if (mapping[c] === 0) delete mapping[c];
left++;
maxCount = getMaxCount(); // 更新最大计数
}
res = Math.max(res, right - left);
}
return res;
function getMaxCount() {
let vals = Object.values(mapping);
return vals.length > 0 ? Math.max(...vals) : 0;
}
};