LeetCode-1208. Get Equal Substrings Within Budget-Analysis and Code (Java)

LeetCode-1208. Make the strings as equal as possible [Get Equal Substrings Within Budget]-analysis and code [Java]

1. Topic

Give you two strings of the same length, s and t.
Changing the i-th character in s to the i-th character in t requires an overhead of |s[i]-t[i]| (the overhead may be 0), which is the difference between the ASCII code values ​​of the two characters Absolute value.
The maximum budget for changing strings is maxCost. When converting strings, the total cost should be less than or equal to the budget, which also means that the conversion of strings may be incomplete.
If you can convert the substring of s into its corresponding substring in t, return the maximum length that can be converted.
If there is no substring in s that can be converted into the corresponding substring in t, 0 is returned.

Example 1:

输入:s = "abcd", t = "bcdf", cost = 3
输出:3
解释:s 中的 "abc" 可以变为 "bcd"。开销为 3,所以最大长度为 3。

Example 2:

输入:s = "abcd", t = "cdef", cost = 3
输出:1
解释:s 中的任一字符要想变成 t 中对应的字符,其开销都是 2。因此,最大长度为 1。

Example 3:

输入:s = "abcd", t = "acde", cost = 0
输出:1
解释:你无法作出任何改动,所以最大长度为 1。

prompt:

  • 1 <= s.length, t.length <= 10^5
  • 0 <= maxCost <= 10^6
  • Both s and t contain only lowercase English letters.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/get-equal-substrings-within-budget
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Double pointer

(1) Thinking

Design two pointers and move the right pointer in turn. If the interval cost is greater than the budget, move the left pointer so that the range of the interval corresponding to the left and right pointers meets the budget requirement, and the maximum length of the interval during the period is the calculated value.

(2) Code

class Solution {
    
    
    public int equalSubstring(String s, String t, int maxCost) {
    
    
        int len = s.length();
        int[] st = new int[len];
        char[] cs = s.toCharArray(), ct = t.toCharArray();
        for (int i = 0; i < len; i++)
            st[i] = Math.abs(cs[i] - ct[i]);
        
        int l = 0, r = 0, cost = 0, ans = 0;
        while (r < len) {
    
    
            cost += st[r++];
            while (cost > maxCost)
                cost -= st[l++];
            ans = Math.max(ans, r - l);
        }
        return ans;
    }
}

(3) Results

Execution time: 4 ms, beating 98.84% of users
in all Java submissions ; memory consumption: 38.6 MB, beating 54.09% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113817698