LeetCode1234. 替換子串得到平衡字符串

1234. Replace the Substring for Balanced String

You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.

A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.

Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.

Return 0 if the string is already balanced.

Example 1:

Input: s = "QWER"
Output: 0
Explanation: s is already balanced.

Example 2:

Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.

Example 3:

Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".

Example 4:

Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".

Constraints:

  • 1 <= s.length <= 10^5
  • s.length is a multiple of 4
  • scontains only 'Q', 'W', 'E' and 'R'.

Hint:

  1. Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4.
  2. That means you need to count the amount of each letter and make sure the amount is enough.

題目:有一個只含有 'Q', 'W', 'E', 'R' 四種字符,且長度爲 n 的字符串。假如在該字符串中,這四個字符都恰好出現 n/4 次,那麼它就是一個「平衡字符串」。給你一個這樣的字符串 s,請通過「替換一個子串」的方式,使原字符串 s 變成一個「平衡字符串」。你可以用和「待替換子串」長度相同的 任何 其他字符串來完成替換。請返回待替換子串的最小可能長度。

思路:雙指針,參考lee215。兩個指針間是待替換的子串,那麼我們只需要保證在兩指針區域外的字符的頻率都小於n/4。如對於QWERQQQQcount[Q]=5,初始指針i=0,那麼指針j需走到倒數第三個位置,才能使得Q的字符數滿足條件,此時替換的子串爲QWERQQ,嘗試右移左指針i,此時count[Q]=3,調整右指針jcount[Q]=2,更新左指針…

工程代碼下載

class Solution {
public:
    int balancedString(string s) {
        unordered_map<int, int> count;
        for (auto c : s)
            count[c]++;

        int n = s.size();
        int k = n / 4;
        int res = n;

        for (int i = 0, j = 0; j < n; ++j) {
            count[s[j]]--;
            while (i < n && count['Q'] <= k && count['W'] <= k &&
                   count['E'] <= k && count['R'] <= k) {
                res = min(res, j - i + 1);
                count[s[i++]] += 1;
            }
        }

        return res;
    }
};

相似的滑窗問題(lee215總結):

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章