424 Longest Repeating Character Replacement The longest repeating character after replacement

Given a string consisting of only uppercase English letters, you can replace any character at any position with another character, up to k times in total. After doing the above, find the length of the longest substring containing repeated letters.
Note:
The string length and k will not exceed 104.
Example 1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace two 'A's with two 'B's and vice versa.
Example 2:
Input:
s = "AABABBA", k = 1
Output:
4
Explanation:
Replace the middle 'A' with 'B', and the string becomes "AABBBBA".
The substring "BBBB" has the longest repeating letter, and the answer is 4.

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

C++:

class Solution {
public:
    int characterReplacement(string s, int k) {
        int res = 0, maxCnt = 0, start = 0;
        vector<int> counts(26, 0);
        for (int i = 0; i < s.size(); ++i)
        {
            maxCnt = max(maxCnt, ++counts[s[i] - 'A']);
            while (i - start + 1 - maxCnt > k)
            {
                --counts[s[start] - 'A'];
                ++start;
            }
            res = max(res, i - start + 1);
        }
        return res;
    }
};

 Reference: https://www.cnblogs.com/grandyang/p/5999050.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324489214&siteId=291194637