Leetcode-1234. 替换子串得到平衡字符串

Problem: 1234. 替换子串得到平衡字符串

思路

滑动窗口+哈希表+贪心思想

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

    Code

    Python3

    class Solution:
        def balancedString(self, s: str) -> int:
            n = len(s)
            ans = n
    
            cnt = Counter(s)
            
            target = n / 4
    
            if max(cnt.values()) <= target:
                return 0
            
            l = 0
            for r,c in enumerate(s):
                cnt[c] -= 1
                while cnt[s[l]] < target:
                    cnt[s[l]] += 1
                    l += 1
                if max(cnt.values()) <= target:
                    ans = min(ans, r - l + 1)
            
            return ans

    你可能感兴趣的:(Leetcode,#滑动窗口,leetcode,算法,哈希算法)