LeetCode 1208. 尽可能使字符串相等

可以通过滑动窗口转化为一个最长序列求和问题,旨在在指定值下,找到总和小于该值的最长序列;

 

如果使用dp动态规划,但是会超时;

class Solution {
public:
    vector<vector<int>>dp;
    int equalSubstring(string s, string t, int maxCost) {
        int len = s.size();
        int maxn = 0;
        dp.resize(len);
        for (int i = 0; i < len; i++) {
            dp[i].resize(len);
        }
        for (int i = 0; i < len; i++) {
                dp[i][i] = abs(s[i] - t[i]);
                if (dp[i][i] <= maxCost)
                    maxn = 1;
        }
        for (int i = 0; i < len - 1; i++) {
            //进行两位字符初始化
            dp[i][i + 1] = dp[i + 1][i] = dp[i][i] + dp[i + 1][i + 1];
            if (dp[i][i + 1] <= maxCost)
                maxn = 2;
        }
        for (int l = 2; l < len; l++) {
            //对长度进行递增枚举;
            for (int i = 0; i < len - l; i++) {
                dp[i][i + l] = dp[i + l][i] = abs(s[i] - t[i]) + abs(s[i + l] - t[i + l])+dp[i+1][i+l-1];
                if (dp[i][i + l] <= maxCost && maxn < l + 1) {
                    maxn = l + 1;
                }
            }
        }
        return maxn;
    }
};

 

可以转换为求指定值下的,最长连续序列加和问题,所以仍然是一个滑动窗口问题;

class Solution {
public:
    vector<int>vec;

    int equalSubstring(string s, string t, int maxCost) {
        vec.resize(s.size());
        for (int i = 0; i < s.size(); i++) {
            vec[i] = abs(s[i] - t[i]);
        }
        int l = 0, r = 0;
        int sum = 0;
        int len = 0;
        while (r < s.size()) {
            sum += vec[r];
            if (sum > maxCost) {
                sum -= vec[l];
                l++;
            }
            len = max(len, r - l + 1);
            r++;
        }
        return len;
    }
};

  

posted @ 2021-02-06 17:34  暮云林凌  阅读(99)  评论(0编辑  收藏  举报