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 end10
if (--cnt[s.charAt(i)] == 0) excess--; // remove letter at index i11
while (excess == 0) { // if no more excess, then12
if (++cnt[s.charAt(j)] == 1) excess++; // we put letter at index j back13
ans = Math.min(i - j + 1, ans);14
; // and update ans accordingly