problem:https://leetcode.com/problems/longest-repeating-character-replacement/
维护一个最多包含k个额外字符的滑动窗口。需要记录当前出现次数最多字符的出现次数来判断窗口是否合法,如果超过了,就把首指针向后挪一位,同时更新最多出现次数。对每个合法窗口,取其中的最大值。
class Solution {
public:
int characterReplacement(
string s,
int k) {
int begin =
0;
int res =
0;
int maxLen =
0;
vector<
int> count(
26,
0);
for(
int i =
0;i < s.size();i++)
// end
{
count[s[i] -
'A']++
;
maxLen = max(maxLen, count[s[i] -
'A']);
int len = i - begin +
1;
if(len > maxLen +
k)
{
count[s[begin] -
'A']--
;
begin++
;
maxLen = *
max_element(count.begin(), count.end());
}
// cout << res << " ";
res = max(res, i - begin +
1);
}
return res;
}
};
转载于:https://www.cnblogs.com/fish1996/p/11337010.html