最长连续字符——经典动态规划/滑动窗口

原题在这里

  概述题意:一个含两种字符的字符串,问在可修改k个以内字符情况下,最长同种字符长度。

滑动窗口真的绝了:

  甚至我还思考了一下为什么不过滤一下窗口中间的最大值,因为是滑动维护。

class Solution
{
    //只要窗口中有任何一个字符出现次数不超过 k,那么这个窗口就是合法的
public:
    int maxConsecutiveAnswers(string &answerKey, int k)
    {
        int n = answerKey.size(), i, j, conT = 0, conF = 0;
        for (i = 0, j = 0; j < n; ++j)
        {
            answerKey[j] == 'T' ? ++conT : ++conF;
            if (conT > k && conF > k)
                answerKey[i++] == 'T' ? --conT : --conF;
        }
        return j - i;
    }
};

动态规划:

虽然但是,还是不太喜欢用,也(暂时)不想看懂。

class Solution
{
public:
    int maxConsecutiveAnswers(string &answerKey, int k)
    {
        int n = answerKey.size();
        auto getAns = [&](char c) -> int
        {
            int sum = 0, i, j;
            for (i = 0, j = 0; j < n; ++j)
            {
                if (answerKey[j] == c)
                    ++sum;
                if (sum > k && answerKey[i++] == c)
                    --sum;
            }
            return j - i;
        };
        return max(getAns('T'), getAns('F'));
    }
};

【Over】

posted @ 2022-03-31 22:28  Renhr  阅读(69)  评论(0)    收藏  举报