地址:https://leetcode-cn.com/problems/longest-repeating-character-replacement/
思路:思維
遍歷子串的右端點r,同時記錄過程中所滿足條件的最大相同字符個數Max,對於r-l-Max>k的情況,則右移左端點l直至滿足條件,最後保留最大值r-l即可
Code:
#include<iostream>
using namespace std;
class Solution {
public:
int characterReplacement(string s, int k) {
int a[30]={0},n=s.length();
int res=0,Max=0,l=-1,r=0;
while(r<n){
++a[s[r]-'A'];
Max=max(Max,a[s[r]-'A']);
while(r-l-Max>k){
--a[s[++l]-'A'];
}
res=max(res,r-l);
++r;
}
return res;
}
};
int main()
{
ios::sync_with_stdio(false);
int m;
string s;
Solution So;
cin>>s>>m;
int res=So.characterReplacement(s,m);
cout<<res<<endl;
return 0;
}