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

给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。

注意:字符串长度 和 k 不会超过 104。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-repeating-character-replacement
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int characterReplacement(String s, int k) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int[] cnt = new int[26];
        int left = 0, right = 0;
        int max = 0;
        while (right < s.length()) {
            cnt[s.charAt(right) - 'A']++;
            max = Math.max(max, cnt[s.charAt(right) - 'A']);
            if (right - left + 1 - max > k) {
                cnt[s.charAt(left++) - 'A']--;
            }
            right++;
        }
        return right - left;
    }
}
posted @ 2022-01-18 15:07  Tianyiya  阅读(26)  评论(0)    收藏  举报