zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    nginx 安装配置
    mysql分表
    冲刺day7
    冲刺day6
    冲刺day5
    冲刺day4
    冲刺day3
    冲刺day2
    冲刺day1
    撰写《需求规格说明书》的工作流程、组员分工和组员工作量比例
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13171739.html
Copyright © 2011-2022 走看看