Thursday, December 15, 2016

Longest Repeating Character Replacement -- LeetCode 424

[Question]
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.
[Analysis]
Use a sliding window [j,i] on the string. When the length of the window (i-j+1 - count of most repeating letters) <= k, move ending point i forward and the sub strings in the window are candidates. When the length - count of most repeating letters > k, move starting point j forward until the sub string in window contains the candidate.

Similar to the "Minimum Window Sub-String" problem.

[Solution]
class Solution {
public:
    int characterReplacement(string s, int k) {
        vector<int> counters(26,0);
        int j=0, max_cnt=0;
        int res = 0;
        for (int i=0; i<s.size(); i++) {
            counters[s[i]-'A']++;
            max_cnt = max(max_cnt, counters[s[i]-'A']);
            while (i-j+1 -max_cnt > k) {
                counters[s[j]-'A']--, j++;
                max_cnt = *max_element(counters.begin(), counters.end());
            }
            res = max(res, i-j+1);
        }

        return res;
    }
};

No comments:

Post a Comment