尽可能使字符串相等

思路

(1)双下标指针l和r,初始值为0;
(2)记录当前已使用的usrCost,初始化为0;
(3)遍历每次计算当前绝对值fooCost,如果usrCost加上fooCast大于maxCost,就让l右移,
然后将usrCost减去abs(s[l] - t[l]),直到l < r不成立或者可以将fooCost放入时结束循环。
(4)在(3)步骤中,记录下最大的max_num

  int equalSubstring(string s, string t, int maxCost) {
        int n = s.size();
        int l = 0;
        int r = 0;
        int usrCost = 0;
        int max_num = 0;
        while(r < n) {
            int fooCost = abs(s[r] - t[r]);
            while (l <= r && usrCost + fooCost > maxCost) {
                usrCost -= abs(s[l] - t[l]);
                l++;
            }
            usrCost += fooCost;
            max_num = std::max(max_num, (r - l + 1));
            r++;
        }
        return max_num;
    }
posted @ 2021-07-12 10:53  cyssmile  阅读(51)  评论(0)    收藏  举报