问题描述
小R有一个由小写字母组成的字符串 str1,长度为 n。字符串中有些位置的字符可以通过修复操作来修改为 a-z 中的任意一个字母,这个修复操作最多可以进行 m 次。现在,小R想知道,经过最多 m 次修复操作后,字符串中由相同字符组成的最长连续子串的最大长度是多少。
注意,str2表示哪些下标可以修改,如果为1那么就可以修改,如果为0那么就不行。
测试样例
样例1:
输入:
n = 5, m = 2, str1 = "abcda", str2 = "01110"
输出:3
样例2:
输入:
n = 7, m = 2, str1 = "abbaccb", str2 = "1001001"
输出:4
样例3:
输入:
n = 3, m = 0, str1 = "aab", str2 = "101"
输出:2
#include <algorithm>
#include <iostream>
using namespace std;
int solution(int n, int m, std::string str1, std::string str2) {
int max_len = 0;
for (char c = 'a'; c <= 'z'; ++c) {
int left = 0;
int modify = 0;
int current_max = 0;
for (int right = 0; right < n; ++right) {
if (str1[right] != c) {
if (str2[right] == '1') {
modify++;
} else {
left = right + 1;
modify = 0;
continue;
}
}
while (modify > m) {
if (str1[left] != c && str2[left] == '1') {
--modify;
}
++left;
}
current_max = max(current_max, right - left + 1);
}
max_len = max(max_len, current_max);
}
return max_len;
}
int main() {
// Add your test cases here
std::cout << (solution(5, 2, "abcda", "01110") == 3) << std::endl;
std::cout << (solution(7, 2, "abbaccb", "1001001") == 4) << std::endl;
std::cout << (solution(3, 0, "aab", "101") == 2) << std::endl;
return 0;
}