defcheck(): if cnt['Q'] > partial or \ cnt['W'] > partial or \ cnt['E'] > partial or \ cnt['R'] > partial: returnFalse returnTrue
if check(): return0
res = len(s) r = 0 for l, c inenumerate(s): while r < len(s) andnot check(): cnt[s[r]] -= 1 r += 1 ifnot check(): break res = min(res, r - l) cnt[c] += 1 return res
classSolution { public: intidx(constchar& c){ return c - 'A'; }
intbalancedString(string s){ vector<int> cnt(26); for (auto c : s) { cnt[idx(c)]++; }
int partial = s.size() / 4; int res = s.size(); auto check = [&]() { if (cnt[idx('Q')] > partial || cnt[idx('W')] > partial \ || cnt[idx('E')] > partial || cnt[idx('R')] > partial) { returnfalse; } returntrue; };
if (check()) { return0; } for (int l = 0, r = 0; l < s.size(); l++) { while (r < s.size() && !check()) { cnt[idx(s[r])]--; r++; } if (!check()) { break; } res = min(res, r - l); cnt[idx(s[l])]++; } return res; } };
intbalancedString(char * s) { int cnt[26]; memset(cnt, 0, sizeof(cnt)); for (int i = 0; s[i] != '\0'; i++) { cnt[idx(s[i])]++; }
int len = strlen(s); int partial = len / 4; int res = len; if (check(cnt, partial)) { return0; } for (int l = 0, r = 0; l < len; l++) { while (r < len && !check(cnt, partial)) { cnt[idx(s[r])]--; r++; } if (!check(cnt, partial)) { break; } res = MIN(res, r - l); cnt[idx(s[l])]++; } return res; }
funcbalancedString(s string)int { cnt := map[byte]int{} for _, c := range s { cnt[byte(c)]++ } partial := len(s) / 4 check := func()bool { if cnt['Q'] > partial || cnt['W'] > partial || cnt['E'] > partial || cnt['R'] > partial { returnfalse } returntrue }
if check() { return0 }
res := len(s) r := 0 for l, c := range s { for r < len(s) && !check() { cnt[s[r]]-- r += 1 } if !check() { break } res = min(res, r-l) cnt[byte(c)]++ } return res }
funcmin(a, b int)int { if a > b { return b } return a }