题目
思路 滑动窗口
替换字符可以有T和F两种情况。遍历字符串,如果遇到字符与要替换的字符相同,就让cnt++,并更新结果ans = max(ans, j - i + 1)。如果cnt>k,就让滑动窗口的左边界右移,并更新cnt的值,直到cnt<=k。
代码
class Solution {
public:
string s;
int n, k;
int maxConsecutiveAnswers(string answerKey, int _k) {
s = answerKey;
n = answerKey.size();
k = _k;
return max(getCnt('T'), getCnt('F'));
}
int getCnt(char c){
int ans = 0;
for(int i = 0, j = 0, cnt = 0; j < n; j++){
if(s[j] == c) cnt++;
while(cnt > k){
if(s[i] == c) cnt--;
i++;
}
ans = max(ans, j - i + 1);
}
return ans;
}
};