题解 | #编程题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; }