1. 程式人生 > >[LeetCode] Longest Repeating Character Replacement 最長重複字元置換

[LeetCode] 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.

這道題給我們了一個字串,說我們有k次隨意置換任意字元的機會,讓我們找出最長的重複字元的字串。這道題跟之前那道Longest Substring with At Most K Distinct Characters很像,都需要用滑動視窗Sliding Window來解。我們首先來想,如果沒有k的限制,讓我們求把字串變成只有一個字元重複的字串需要的最小置換次數,那麼就是字串的總長度減去出現次數最多的字元的個數。如果加上k的限制,我們其實就是求滿足(子字串的長度減去出現次數最多的字元個數)<=k的最大子字串長度即可,搞清了這一點,我們也就應該知道怎麼用滑動視窗來解了吧我們用一個變數start記錄滑動視窗左邊界,初始化為0,然後我們遍歷字串,每次累加出現字元的個數,然後更新出現最多字元的個數,然後我們判斷當前滑動視窗是否滿足之前說的那個條件,如果不滿足,我們就把滑動視窗左邊界向右移動一個,並注意去掉的字元要在counts裡減一,直到滿足條件,我們更新結果res即可,參見程式碼如下:

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;
    }
};

類似題目:

參考資料: