class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
left, right, res, cost = 0, 0, 0, 0
while right < len(s):
# 统计转化当前字符所需开销
cost += abs(ord(s[right]) - ord(t[right]))
# 窗口向右移动
right += 1
# 如果当前开销小于最大预算
# 且当前长度大于已有字符串的长度
if cost <= maxCost and right - left > res:
res = right - left
# 如果当前开销大于最大开销
# 缩小窗口的左边界
# 同时更新当前开销
# 注意: 只能是大于
if cost > maxCost:
cost -= abs(ord(s[left]) - ord(t[left]))
left += 1
return res
1208. 尽可能使字符串相等(滑动窗口)
最新推荐文章于 2021-02-05 20:07:44 发布