双指针问题一般左边需要不停移动知道满足规律,但在这个最大窗口问题中,可以不让左边的一直移动,只要每次移动一次即可。设置默认窗口大小为0,如果不动,就维持窗口,这样能维持住最大窗口,最后只要返回左右指针的差即可。相比普通的双指针能减少一半左右的时间。注:维护最大窗口无需判断左指针和右指针相对位置,只看条件就行。
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
def getCost(c1, c2):
return abs(ord(c1)-ord(c2))
l, r = 0, 0
costs = 0
while r < len(s):
costs += getCost(s[r], t[r])
if costs > maxCost:
costs -= getCost(s[l], t[l])
l += 1
r += 1
return r-l