Given a string s that consists of only uppercase English letters, you can perform at most koperations on that string.
In one operation, you can choose any character of the string and change it to any other uppercase English character.
Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
Example 1:
Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.
参考资料:here。
class Solution {
public:
int characterReplacement(string s, int k) {
int left = 0, right = 0;
vector<int> counts(26, 0);
int ans = 0;
while (right < s.size()) {
int max_len = 0;
counts[s[right] - 'A']++;
for(int c:counts) max_len = max(max_len, c);
int window = right - left;
if (window - max_len < k) {
right++;
}
else {
counts[s[left] - 'A']--;
left++;
right++;
}
ans = max(ans,right-left);
}
return ans;
}
};
版权声明:本文为m0_37518259原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。