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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容