424. Longest Repeating Character Replacement

Posted duan-decode

tags:

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

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string‘s length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two ‘A‘s with two ‘B‘s or vice versa.

 

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one ‘A‘ in the middle with ‘B‘ and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
class Solution {
public:
    //滑动窗法
    int characterReplacement(string s, int k) {
        vector<int>count(26);   //记录‘A‘,‘B‘..的个数
        int i = 0,j=0;
        int n = s.size();
        if(n==0) return 0;
        int length = INT_MIN;
        while(j<n)
        {
            count[s[j]-A]++;
            while(j-i+1-max_repeating(count)>k)     //对以i开始窗口左边界延伸的最大右边界只能到j时(窗口大小减窗口中最多的元素得到需要替换的数目)
            {
                count[s[i]-A]--;
                i++;
            }
            length = max(length,j-i+1);             //更新最大窗口大小
            j++;
        }
        return length;
    }
    
    int max_repeating(vector<int>count)
    {
        int res = 0;
        for(int i= 0;i<count.size();i++)
            res = max(res,count[i]);
        return res;
    }
};

 


以上是关于424. Longest Repeating Character Replacement的主要内容,如果未能解决你的问题,请参考以下文章

424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement - Medium

[滑动窗口] leetcode 424 Longest Repeating Character Replacement

[LeetCode] 424. Longest Repeating Character Replacement

leetcode 3. Longest Substring Without Repeating Characters (Python版)

[LeetCode] Longest Substring Without Repeating Characters