传送🚪
You are given a string S[1…N] containing only lowercase letters. Now you need to find the longest substring S[l…r] such that every letter (a
to z
) appears no more than K times in the substring. You just need to output the length (r−l+1) of the longest substring.
Input
There are multiple test cases.
Each test case contains one integer K (1≤K≤N) and one string S in one line.
It’s guaranteed that the sum of lengths of the input strings is no more than 4×105.
Output
For each test case, print one integer in one line, denoting the length of the longest substring.
Sample Input
1 abcabcabc
2 abcabcabc
2 aaabbbccc
Sample Output
3
6
4
题意:给出数字k和一个字符串,求最长的子字符串为多长(要去子字符串的相同字符出现次数不超过k次)
分析:标记一个子字符串起始点,然后从头book数组标记,当有字符次数超过k次的时候,从标记的起始点开始,边加回之前标记的次数变找哪个字符超过了k次,找到后更新起始点,过程中更新字符串长度最大值。
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char a[400010];
int vis[200];
int main()
{
int k,l,r,flag,ans,i,j,ii,fr;
while(~scanf("%d",&k))
{
scanf("%s",a);
memset(vis,0,sizeof(vis));
l=strlen(a);
ans=0;
for(r=0,fr=0;fr<l;fr++)
{
if(r==l)
break;
while(r<l&&vis[a[r]]<k)
{
vis[a[r]]++;
r++;
}
ans=max(ans,r-fr);
for(;fr<r;fr++)//让起始点取遍历,如果末点r遍历到l,下边有限制.
{
vis[a[fr]]--;
if(a[fr]==a[r])
break;
}
/*或者:
for(j=fr;j<r;j++)
{
vis[a[j]]--;
if(a[j]==a[r])
break;
}
fr=j;*/
//这一步让新的起始点之前的标记数-1.一边减着一边找.明显比注释部分要简单
/*for(j=fr;j<r;j++)
{
if(a[j]==a[r])
{
for(ii=fr;ii<=j;ii++)
vis[a[ii]]--;
fr=ii;
break;
}
}*/
}
printf("%d\n",ans);
}
}
//1 abzdeazxcnm