一、题目描述

给你两个长度相同的字符串,s 和 t。
将 s 中的第 i 个字符变到 t 中的第 i 个字符需要 |s[i] - t[i]| 的开销(开销可能为 0),也就是两个字符的 ASCII 码值的差的绝对值。
用于变更字符串的最大预算是 maxCost。在转化字符串时,总开销应当小于等于该预算,这也意味着字符串的转化可能是不完全的。
如果你可以将 s 的子字符串转化为它在 t 中对应的子字符串,则返回可以转化的最大长度。
如果 s 中没有子字符串可以转化成 t 中对应的子字符串,则返回 0。
示例 1:
输入:s = “abcd”, t = “bcdf”, cost = 3
输出:3
解释:s 中的 “abc” 可以变为 “bcd”。开销为 3,所以最大长度为 3。
示例 2:
输入:s = “abcd”, t = “cdef”, cost = 3
输出:1
解释:s 中的任一字符要想变成 t 中对应的字符,其开销都是 2。因此,最大长度为 1。
示例 3:
输入:s = “abcd”, t = “acde”, cost = 0
输出:1
解释:你无法作出任何改动,所以最大长度为 1。

难度:中等
二、题解
方法一:滑动窗口
保证窗口内的maxCost值大于等于零,如果小于0,则需要left++,但是要注意的是左指针向右移动之前要将left对应的cost恢复。
class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {
        int n = min(s.size(),t.size());
        int left = 0;
        int right = 0;
        int ans = 0;
        while(right<n){
            maxCost -= abs(s[right]-t[right]);
            if(maxCost>=0){
                ans = max(ans,right-left+1);
            }else{
                maxCost += abs(s[left]-t[left]);
                left++;
            }
            right++;
        }
        return ans;
    }
};

优化:

class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {
        int n = min(s.size(),t.size());
        int left = 0;
        int right = 0;
        while(right<n){
            maxCost -= abs(s[right]-t[right]);
            if(maxCost<0){
                maxCost += abs(s[left]-t[left]);
                left++;
            }
            right++;
        }
        return right - left;
    }
};

1208. 尽可能使字符串相等(双指针、滑动窗口)

 

 

 

相关文章:

  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
  • 2021-07-22
猜你喜欢
  • 2021-08-15
  • 2021-09-20
  • 2022-12-23
  • 2021-08-21
  • 2022-12-23
  • 2022-01-07
  • 2021-08-08
相关资源
相似解决方案