longest-repeating-character-replacement(难)

Posted 笨鸟居士的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了longest-repeating-character-replacement(难)相关的知识,希望对你有一定的参考价值。

用sliding window的方法,之前还有个k不同元素好像也是类似的思路。有时间可以去复习下。

https://leetcode.com/problems/longest-repeating-character-replacement/

// sliding window

public class Solution {
    public int characterReplacement(String s, int k) {

        int[] count = new int[26];
        
        int maxch = -1; // the char with max count in current substr
        int max = 0; // the max count for single char in current substr
        int len = 0; // current substr length
        int ret = 0; // final result

        for (int i=0; i<s.length(); i++) {
            int tmp = s.charAt(i) - ‘A‘;
            count[tmp]++;
            len++;

            if (maxch == tmp) {
                max++;
            }
            else {
                if (count[tmp] > max) {
                    max = count[tmp];
                    maxch = tmp;
                }
            }

            if (len - max <= k) {
                if (len > ret) {
                    ret = len;
                }
            }

            while (len - max > k) {
                int newTmp = s.charAt(i-len+1) - ‘A‘;
                count[newTmp]--;
                len--;
                if (maxch == newTmp) {
                    max--;
                    for (int j=0; j<26; j++) {
                        if (count[j] > max) {
                            max = count[j];
                            maxch = j;
                        }
                    }
                }
            }
        }
        return ret;
    }
}

 

以上是关于longest-repeating-character-replacement(难)的主要内容,如果未能解决你的问题,请参考以下文章