equalSubstring-make strings equal as much as possible

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:

Input: s = "abcd", t = "bcdf", cost = 3
Output: 3
Explanation: "abc" in s can be changed to "bcd". The cost is 3, so the maximum length is 3.

Example 2:

Input: s = "abcd", t = "cdef", cost = 3
Output: 1
Explanation: If any character in s wants to become the corresponding character in t, the cost is 2. Therefore, the maximum length is 1.

Example 3:

Input: s = "abcd", t = "acde", cost = 0
Output: 1
Explanation: You cannot make any changes, so the maximum length is 1.

prompt:

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

Related Topics Array Sliding Window

Problem-solving ideas

Similar ideas
to the previous article. Reference link- the longest repeated character after replacement

Problem-solving code:

class Solution {
    
    
    public int equalSubstring(String s, String t, int maxCost) {
    
    
        int len=s.length();
        int[] nums=new int[len];
        int right=0,left=0;
        int sum=0;
        for (right = 0; right < len; right++) {
    
    
            nums[right]=Math.abs(s.charAt(right)-t.charAt(right));
            sum+=nums[right];
            //sum+=Math.abs(s.charAt(right)-t.charAt(right));
            if(maxCost<sum)
            {
    
    
//                sum-=Math.abs(s.charAt(left)-t.charAt(left));
//                left++;
                sum-=nums[left++];
            }
        }
        return right-left;
    }
}

effect:

The info
answer was successful:
execution time: 6 ms, beating 78.81% of Java users
Memory consumption: 38.7 MB, beating 26.17% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113702966