美文网首页
1208. Get Equal Substrings Withi

1208. Get Equal Substrings Withi

作者: morningstarwang | 来源:发表于2021-02-05 17:38 被阅读0次

    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 Withi

          本文链接:https://www.haomeiwen.com/subject/jxrgtltx.html