1208. Get Equal Substrings Within Budget

Ref: https://leetcode-cn.com/problems/candy/

这道题思路和424类似,利用双指针可以快速实现,主要思路如下:

  • 左指针不动,移动右指针计算cost,直到超过maxCount;
  • 左指针移动一个单位,继续上述操作,直到right到达尾部。

代码如下:

class Solution:

    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
        l = len(s)
        s = [x for x in s]
        t = [x for x in t]
        left = 0
        right = 0
        result = 0
        max_cost = 0
        while right < l:
            max_cost += abs(ord(s[right]) - ord(t[right]))
            right += 1
            if max_cost > maxCost:
                max_cost -= abs(ord(s[left]) - ord(t[left]))
                left += 1
            result = max(result, right - left)
        return result

你可能感兴趣的:(1208. Get Equal Substrings Within Budget)