一、题目
You are given a string s of length n containing only four 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 s balanced. If s is already balanced, return 0.
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”.
Constraints:
n == s.length
4 <= n <= 105
n is a multiple of 4.
s contains only ‘Q’, ‘W’, ‘E’, and ‘R’.
二、题解
滑动窗口,如果l-r上可以随便填,是否能满足要求,遍历找最小的窗口(l和r都只会向右移动)
class Solution {
public:
int balancedString(string s) {
int n = s.size(),res = n;
int req = n / 4;
vector<int> arr(n,0);
vector<int> cnt(4,0);
for(int i = 0;i < n;i++){
if(s[i] == 'Q') arr[i] = 0;
else if(s[i] == 'W') arr[i] = 1;
else if(s[i] == 'E') arr[i] = 2;
else arr[i] = 3;
cnt[arr[i]]++;
}
for(int l = 0,r = 0;l < n;l++){
while(!ok(cnt,r-l,req) && r < n) cnt[arr[r++]]--;
if(ok(cnt,r-l,req)) res = min(res,r-l);
cnt[arr[l]]++;
}
return res;
}
bool ok(vector<int> cnt,int len,int req){
for(int i = 0;i < 4;i++){
if(cnt[i] > req) return false;
len -= req - cnt[i];
}
return len == 0;
}
};