def balancedString(self, s):
"""
:type s: str
:rtype: int
"""
#思路找到最小窗口,使窗口外的元素都小于等于s//4,窗口内的元素就是要替换的
#如‘WQWRQQQW’,因为s的长度是4的倍数
#我们需要换掉2Q和1W,不在意要换成什么
#也就是找到包含2Q1W的最小窗口
#窗口包含2Q1W的时候是窗口外的元素都是小于等于s//4的
#所以先计算每个元素数量,之后扩大窗口到满足条件
#之后再尝试缩小窗口
dict_rec = Counter(s)
n = len(s)/4
l = 0
res = len(s)
if dict_rec["Q"] <= n and dict_rec["W"] <= n and dict_rec["E"] <= n and dict_rec["R"] <= n:
return 0
for r in range(len(s)):
dict_rec[s[r]] -= 1
while l <= r and dict_rec["Q"] <= n and dict_rec["W"] <= n and dict_rec["E"] <= n and dict_rec["R"] <= n: #窗口外元素都小于s//4
res = min(res,r-l+1) #满足时更新答案
dict_rec[s[l]] += 1
l += 1 #尝试缩小窗口看是否满足
return res
leetcode1234. 替换子串得到平衡字符串
最新推荐文章于 2023-02-15 11:44:58 发布