【滑窗】B017_LC_儘可能使字符串相等(預處理字符差)

一、Problem

You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters.

You are also given an integer maxCost.

Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of twith a cost less than or equal to maxCost.

If there is no substring from s that can be changed to its corresponding substring from t, return 0.

Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3.

Constraints:

1 <= s.length, t.length <= 10^5
0 <= maxCost <= 10^6
s and t only contain lower case English letters.

二、Solution

方法一:滑窗

  • 窗口的含義
    • 在預算範圍內最大長度
  • 窗口右邊界移時機
    • 每次都右移
  • 窗口左邊界移時機
    • 當預算不足時
  • 結算時機
    • 窗口左邊移動
class Solution {
    public int equalSubstring(String s, String t, int c) {
        int l = 0, r = 0, n = s.length(), ans = 0, d[] = new int[n];
        for (int i = 0; i < n; i++) d[i] = Math.abs(s.charAt(i)-t.charAt(i));

        while (r < n) {
            c -= d[r];
            while (l <= r && c < 0) {
                c += d[l++];
            }
            ans = Math.max(ans, r-l+1);
            r++;
        }  
        return ans;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章