1208. Get Equal Substrings Within Budget

Posted habibah-chang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1208. Get Equal Substrings Within Budget相关的知识,希望对你有一定的参考价值。

问题:

给定两个等长字符串s和t,相同index上的元素差值为cost

求cost和最大不超过maxCost,所满足的最长子串的长度。

Example 1:
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.

Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to charactor in t, so the maximum length is 1.

Example 3:
Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You can‘t make any change, so the maximum length is 1.
 
Constraints:
1 <= s.length, t.length <= 10^5
0 <= maxCost <= 10^6
s and t only contain lower case English letters.

  

解法:

sliding window

每个元素的权值为 abs(s[i]-t[i])

求最大窗口,使得权值之和<=maxCost

 

?? 注意:这里j代表右边界,i代表左边界。

每次首先向右移动右边界,使得j增大,满足条件的情况下,i不变化。所得结果res=j-i也就依次增大。

但当j增大后,超过maxCost,不满足条件了,那么i增大,缩小窗口,但是下一次循环中 j也增大,res是不变的。

之后的窗口尝试只会超过现在的窗口大小。

也就是说,只有当下次res大于现在的res, 且再满足条件的时候,会用新的res替换掉现在的res。

代码参考:

 1 class Solution {
 2 public:
 3     int equalSubstring(string s, string t, int maxCost) {
 4         int N=s.size();
 5         int i=0, j=0;
 6         for(j=0; j<N; j++){
 7             if((maxCost-=abs(s[j]-t[j]))<0){
 8                 maxCost+=abs(s[i]-t[i]);
 9                 i++;
10             }
11         }
12         return j-i;
13     }
14 };

 

以上是关于1208. Get Equal Substrings Within Budget的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

Java 子字符串的比较(substring的==与equal()使用)

“==”和equal的比较

28. Implement strStr()