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 of4
s
contains only'Q'
,'W'
,'E'
and'R'
.
Hint:
- Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4.
- 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
。如对于QWERQQQQ
,count[Q]=5
,初始指针i=0
,那么指针j
需走到倒数第三个位置,才能使得Q
的字符数满足条件,此时替换的子串为QWERQQ
,尝试右移左指针i
,此时count[Q]=3
,调整右指针j
,count[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总结):