题目定义:
给你两个长度相同的字符串,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。
方式一(滑动窗口):
class Solution {
public int equalSubstring(String s, String t, int maxCost) {
int[] costs = new int[s.length()];
int fast = 0,slow = 0,ans = 0;
for(int i = 0; i < s.length(); i++){
costs[i] = Math.abs(s.charAt(i) - t.charAt(i));
}
while(fast < costs.length){
maxCost -= costs[fast];
if(maxCost < 0){
maxCost +=costs[slow];
slow++;
}
ans = Math.max(ans,fast - slow + 1);
fast++;
}
return ans;
}
}
方式二(前缀和+二分查找):
class Solution {
public int equalSubstring(String s, String t, int maxCost) {
int[] accDiff = new int[s.length() + 1];
int ans = 0;
for(int i = 0; i < s.length(); i++){
accDiff[i + 1] = accDiff[i] + Math.abs(s.charAt(i) - t.charAt(i));
}
for(int i = 1; i <= s.length(); i++){
int index = binarySearch(accDiff,i,accDiff[i] - maxCost);
ans = Math.max(ans,i - index);
}
return ans;
}
private int binarySearch(int[] accDiff,int end,int target){
int low = 0,high = end;
while(low < high){
int mid = (high - low) / 2 + low;
if(accDiff[mid] < target)
low = mid + 1;
else high = mid;
}
return low;
}
}
参考:
https://leetcode-cn.com/problems/get-equal-substrings-within-budget/solution/jin-ke-neng-shi-zi-fu-chuan-xiang-deng-b-higz/