【Leetcode】滑动窗口

题目

  1. 尽可能使字符串相等

给你两个长度相同的字符串,s 和 t。

将 s 中的第 i 个字符变到 t 中的第 i 个字符需要 |s[i] - t[i]| 的开销(开销可能为 0),也就是两个字符的 ASCII 码值的差的绝对值。

用于变更字符串的最大预算是 maxCost。在转化字符串时,总开销应当小于等于该预算,这也意味着字符串的转化可能是不完全的。

如果你可以将 s 的子字符串转化为它在 t 中对应的子字符串,则返回可以转化的最大长度。

如果 s 中没有子字符串可以转化成 t 中对应的子字符串,则返回 0。

解题思路

  1. 双指针

代码

class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {
        int left=0, res=0;
        int n = s.size();
        int curCost = 0;
        for(int right=0;right<n;right++)
        {
            curCost += abs((s[right]-'A')-(t[right]-'A'));
            if (curCost>maxCost)
            {
                curCost -= abs((s[left]-'A')-(t[left]-'A')); 
                left++;
            }
            res = max(res, right-left+1);
        }
        return res;

    }
};

python

class Solution:
    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
        left=0
        n = len(s)
        curCost = 0
        res = 0
        for right in range(n):
            curCost += abs(ord(t[right])-ord(s[right]))
            print(curCost)
            if curCost>maxCost:
                curCost-=abs(ord(t[left])-ord(s[left]))
                left+=1
            else:
                res = max(res, right-left+1)
        return res




posted @ 2022-05-03 21:50  jucw  阅读(37)  评论(0编辑  收藏  举报