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?

Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.
The second line contains the string, consisting of letters ‘a’ and ‘b’ only.

Output
Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

Examples
Input

4 2
abba

Output

4

Input

8 1
aabaabaa

Output

5

这个题的意思是是给你一个长度为n并且只含ab的字符串,并且有k次修改机会,使得修改完后的字符串得到一个有最长的含有连续相同字母的子串长度。

题目分析:
首先,用a[]、b[]数组分别存储第i位到第一位中a的数量和b的数量。
然后枚举所有点,将其做为起点,然后往后用二分寻找终点,用ans存储找到最大的长度即可。

上代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
#include <iomanip>
#define LL long long
const int N=1e5+5;
using namespace std;
int  a[N],b[N];
char s[N]; 
int main()
{
 cin.tie(0);                  //解除cin和cout的绑定加快cin的速度
 ios::sync_with_stdio(false); //再次加快cin的速度,但不能再用scanf了
 int n,k;
 cin>>n>>k;
 cin>>s+1;
 for(int i=1;i<=n;i++)
 {                            //a存储s的1-i中a的个数,b存储s的1-i中b的个数               
  if(s[i]=='a') a[i]=a[i-1]+1,b[i]=b[i-1];
  else a[i]=a[i-1],b[i]=b[i-1]+1;
 }
 int ans=0;
 for(int i=1;i<=n;i++)
 {
  int l=i,r=n,mid;
  while(r>=l)                //二分查找终点
  {
   mid=l+r>>1;
   if(a[mid]-a[i-1]<=k||b[mid]-b[i-1]<=k)
   {                         //如果a或b的的数量小于等于k(即修改小于k次)
       ans=max(ans,mid-i+1);//则满足条件用其长度与ans比较,求最大值
       l=mid+1; 
   }
   else r=mid-1;
   }
 }
 cout<<ans<<endl;     //输出答案
 return 0;
}
发布了16 篇原创文章 · 获赞 4 · 访问量 902

猜你喜欢

转载自blog.csdn.net/li_wen_zhuo/article/details/104756581
今日推荐