1# Runtime: 450 ms (Top 49.65%) | Memory: 14.6 MB (Top 82.17%)2class Solution:3def balancedString(self, s):4count = collections.Counter(s)5res = n = len(s)6if all(n / 4 == count[char] for char in "QWER"):7return 08left = 09for right, char in enumerate(s):10# replace char whose index==right to check if it is balanced11count[char] -= 112# if it is balanced, window shrinks to get the smallest length of window13while left <= right and all(n / 4 >= count[char] for char in "QWER"):14res = min(res, right - left + 1)15count[s[left]] = count[s[left]] + 116left += 117return res