题意 :
- 给一个x.串,每次操作可以将一个.换成一个x,问0-k次操作的过程中,连续的x的数量最多是多少
思路 :
- 转换条件,就是我们最多可以将k个.换成x
- 在所有满足.数小于等于k的区间中,最大的区间长度就是答案;优化一下,
- 显然这会超时,我们的优化方案是 :1.前缀和(因为要求区间内的.数量);2.滑动窗口算法(外层循环左边界,每次往右移动一个,内层循环右边界,找到
恰好
能让这个区间内个数小于等于k的最大的右边界,注意这种循环方式得到的r是恰好让区间内数量大于k的) - 输入字符串又没有给其长度,我们先预处理出来,注意-1,因为我们给它加了个空格字符
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <unordered_set>
#include <math.h>
#define endl '\n'
#define fi first
#define se second
#define pb push_back
using namespace std;
using ll = long long;
typedef pair<int, int> PII;
int main()
{
cin.tie(nullptr) -> sync_with_stdio(false);
string s; cin >> s;
s = " " + s;
ll k; cin >> k;
ll n = s.size() - 1;
vector<int> cnt(n + 1);
for (int i = 1; i <= n; i ++ )
{
if (s[i] == '.') cnt[i] = cnt[i - 1] + 1;
else cnt[i] = cnt[i - 1];
}
ll r = 1, ans = 0;
for (ll l = 1; l <= n; l ++ )
{
while (r <= n && cnt[r] - cnt[l - 1] <= k)
r ++ ;
ans = max(ans, r - 1 - l + 1);
}
cout << ans << endl;
return 0;
}