题解 | #编程题2# 滑动窗口+哈希表 C++实现

编程题2

https://www.nowcoder.com/practice/dcc301bc11a7420b88afdbd272299809

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
    int n,m;
    string str;
    cin>>n>>m>>str;
    int l=0;
    int r=1;
    int mxlen = 1;
    unordered_map<char, int> mp; 
    mp[str[0]]=1;
    char other;
    while(r!=str.length())
    {
        mp[str[r]]++;
        if(mp['a']>mp['b'])
        {
            other = 'b';
        }
        else {
            other = 'a';
        }

        while(mp[other]>m)
        {
            mp[str[l]]--;
            l++;
            if(mp['a']>mp['b'])
            {
                other = 'b';
            }
            else {
                other = 'a';
            }
        }
        mxlen = max(mxlen,r-l+1);
        r++;
    }
    cout<<mxlen;
    return 0;
}

全部评论

相关推荐

05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:47
机械打工仔:你自己匿名可以,这么好的公司就别给它匿名了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务