[424. 替换后的最长重复字符](https://leetcode-cn.com/problems/longest-repeating-character-replacement/)

题目描述

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

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

题目解析

最多替换k次,即替换k次,这些被替换的字符串也是逻辑连续的。即求窗口中的字符符合其中最大的字母的个数N和滑动窗口大小M,有M-N<=K,这就得出窗口收缩的条件M-N>K

题目特征

  • 划分为两类事物,滑动窗口内个数最多的数字和其他
  • 需要求出滑动窗口的收缩条件
  • 保证滑动窗口里面东西是连续的

题目解答

class Solution {
    public int characterReplacement(String s, int k) {
        //
        char[] chs = s.toCharArray();
        int len = s.length();
        int[] dict = new int[26];
        int maxc = 0,l=0,res=0;
        for(int r =0 ; r < len ; r++){
           dict[chs[r]-'A']++;
            maxc = Math.max(maxc,dict[chs[r]-'A']);
            while(r-l+1-maxc >k){
                dict[chs[l++]-'A']--;
            }
                
            res = Math.max(r-l+1,res);
        }
        return res;
    }
}

题目总结

问题分割为两部分

posted @ 2019-06-04 10:01  随风而行-  阅读(243)  评论(0编辑  收藏  举报