424.替换后的最长重复字符
链接:424.替换后的最长重复字符
难度:Medium
标签:哈希表、字符串、滑动窗口
简介:给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
题解 1 - typescript
- 编辑时间:2021-02-02
- 执行用时:140ms
- 内存消耗:41.6MB
- 编程语言:typescript
- 解法介绍:[参考链接](https://leetcode-cn.com/problems/longest-repeating-character-replacement/solution/ti-huan-hou-de-zui-chang-zhong-fu-zi-fu-n6aza/)。
function characterReplacement(s: string, k: number): number {
  const num = new Array(26).fill(0);
  const n = s.length;
  const compute = (i: number) => s[i].charCodeAt(0) - 'A'.charCodeAt(0);
  let max = 0,
    left = 0,
    right = 0;
  while (right < n) {
    num[compute(right)]++;
    max = Math.max(max, num[compute(right)]);
    if (right - left + 1 - max > k) {
      num[compute(left)]--;
      left++;
    }
    right++;
  }
  return right - left;
}