仅供自己学习
题目:
Given a string s that consists of only uppercase English letters, you can perform at most k operations 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.
思路:
寻找最大字串,还是滑动窗口算法。其中细节的处理就是如何利用k这个条件。我们可以计数left到right之间的所有的字母分别有多少个,然后再减去最大的,也就是最多的也就是其他字母应该转化成的字母的个数,如果差大于k,则该窗口的子串已经在条件约束下获得最大的。那么再右移left,再重复上述过程即可。
代码:
1 class Solution { 2 public: 3 int characterReplacement(string s, int k) { 4 vector<int> nums(26); //26个字母长度的容器,用来在每个字母对应的容器中计数 5 int left=0,right=0; 6 int count; 7 while(right<s.size()){ 8 nums[s[right]-'A']++; //减‘A’是减去对应的ASIC码,让26个字母都能定位到相应容器 9 count=max(count,nums[s[right]-'A']); 10 if(right-left+1-maxn>k){ 11 nums[s[left]-'A']--; 12 13 left++; 14 } 15 right++; 16 } 17 return right-left; 18 } 19 };