雙指針+思維 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章