双指针+思维 Codeforces Round #354 (Div. 2) C题 Vasya and String

Vasya and String

High school student Vasya got a string of length n as a birthday present. This string consists of letters ‘a’ and ‘b’ only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.

Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?


题目大意:一个长为n的字符串,只由字符 a 和 b 构成,最多可以更改 k 次,问更改后连续的子串最长长度,要求子串的字符全部一样;

求的是连续子串最长长度,无形中和双指针联系在一起了,可以分两个部分进行,一个是改 a ,一个是改 b;

先说改 a ,如果区间 [l,r] 的 a 的个数大于 k ,显然 r 不能再往右走,l 要往右走直到 s[l]=a ,减去这个 a ,r 才可以继续往右走,明显的关系就出现了;

代码:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=2000100;
const LL mod=1e9+7;
int n,k,ans;
int main(){
	cin>>n>>k;
	string s;cin>>s;
	int suma=0,sumb=0,l=0;
	for(int r=0;r<s.length();r++){
		if(s[r]=='a') suma++;
		if(suma>k){
			while(s[l]=='b') l++;
			l++;//去掉a 
			suma--;
		}
		ans=max(r-l+1,ans);
	}
	l=0;
	for(int r=0;r<s.length();r++){
		if(s[r]=='b') sumb++;
		if(sumb>k){
			while(s[l]=='a') l++;
			l++;//去掉b
			sumb--; 
		}
		ans=max(r-l+1,ans);
	}
	cout<<ans<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值