1
class Solution {
2
public int balancedString(String s) {
3
int n = s.length(), ans = n, excess = 0;
4
int[] cnt = new int[128];
5
cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n / 4;
6
for (char ch : s.toCharArray())
7
if (++cnt[ch] == 1) excess++; // if count reaches 1, it is extra and to be removed.
8
if (excess == 0) return 0;
9
for (int i = 0, j = 0; i < n; i++) { // i = window right end, j = window left end
10
if (--cnt[s.charAt(i)] == 0) excess--; // remove letter at index i
11
while (excess == 0) { // if no more excess, then
12
if (++cnt[s.charAt(j)] == 1) excess++; // we put letter at index j back
13
ans = Math.min(i - j + 1, ans);
14
; // and update ans accordingly
15
j++;
16
}
17
}
18

19
return ans;
20
}
21
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0