原题地址(中等)

方法1—滑动窗口/双指针

思路

这题与前几天的424.替换字符串如出一辙,用的都是同一个思路。

代码

  1. class Solution:
  2. def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
  3. n = len(s)
  4. cost = [abs(ord(s[i]) - ord(t[i])) for i in range(n)]
  5. l = r = 0
  6. maxLen, curCost = 0, 0
  7. while r < n:
  8. curCost += cost[r]
  9. while curCost > maxCost:
  10. curCost -= cost[l]
  11. l += 1
  12. maxLen = max(maxLen, r - l + 1)
  13. r += 1
  14. return maxLen

时空复杂度

时间O(N) 空间O(N),可优化成O(1)

空间O(1)代码

  1. class Solution:
  2. def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
  3. i = l = r = maxLen = curCost = 0
  4. while r < len(s):
  5. curCost += ( abs( ord(s[r])-ord(t[r]) ) )
  6. while curCost > maxCost:
  7. curCost -= ( abs( ord(s[l])-ord(t[l]) ) )
  8. l += 1
  9. maxLen = max(maxLen, r - l + 1)
  10. r += 1
  11. return maxLen