To balance the string, we need each character (‘Q’, ‘W’, ‘E’, ‘R’) to appear exactly n/4 times. The problem reduces to finding the smallest substring that, if replaced, would make the string balanced. We can use a sliding window to find the minimum window that covers all excess characters.
Count the frequency of each character in the string.
Set the target count for each character as n/4.
Use a sliding window (two pointers) to find the smallest window such that, if we replace it, the remaining string has no character exceeding the target count.
Move the right pointer to expand the window and the left pointer to shrink it while the condition is satisfied.
classSolution {
publicintbalancedString(String s) {
int n = s.length(), ans = n;
int[] cnt =newint[128];
for (char c : s.toCharArray()) cnt[c]++;
int left = 0;
for (int right = 0; right < n; right++) {
cnt[s.charAt(right)]--;
while (left < n && cnt['Q']<= n/4 && cnt['W']<= n/4 && cnt['E']<= n/4 && cnt['R']<= n/4) {
ans = Math.min(ans, right - left + 1);
cnt[s.charAt(left)]++;
left++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defbalancedString(self, s: str) -> int:
from collections import Counter
n = len(s)
cnt = Counter(s)
ans = n
left =0for right in range(n):
cnt[s[right]] -=1while left < n and all(cnt[c] <= n //4for c in'QWER'):
ans = min(ans, right - left +1)
cnt[s[left]] +=1 left +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
public:int balancedString(string s) {
int n = s.size(), ans = n;
vector<int> cnt(128, 0);
for (char c : s) cnt[c]++;
int left =0;
for (int right =0; right < n; ++right) {
cnt[s[right]]--;
while (left < n && cnt['Q'] <= n/4&& cnt['W'] <= n/4&& cnt['E'] <= n/4&& cnt['R'] <= n/4) {
ans = min(ans, right - left +1);
cnt[s[left]]++;
left++;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
funcbalancedString(sstring) int {
n:= len(s)
cnt:= make([]int, 128)
fori:=0; i < n; i++ {
cnt[s[i]]++ }
ans, left:=n, 0forright:=0; right < n; right++ {
cnt[s[right]]--forleft < n&&cnt['Q'] <=n/4&&cnt['W'] <=n/4&&cnt['E'] <=n/4&&cnt['R'] <=n/4 {
ifans > right-left+1 {
ans = right-left+1 }
cnt[s[left]]++left++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funbalancedString(s: String): Int {
val n = s.length
val cnt = IntArray(128)
for (c in s) cnt[c.code]++var ans = n
var left = 0for (right in0 until n) {
cnt[s[right].code]--while (left < n && cnt['Q'.code] <= n/4&& cnt['W'.code] <= n/4&& cnt['E'.code] <= n/4&& cnt['R'.code] <= n/4) {
ans = minOf(ans, right - left + 1)
cnt[s[left].code]++ left++ }
}
return ans
}
}