Substring
hdu-6948
Problem Description
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
题解:尺取法遍历,长度为满足条件的最大长度,遍历下一个元素就将上个元素删掉。
#include<bits/stdc++.h>
using namespace std;
char c[9000000];
int book[30];
int n,m;
int main()
{
while(cin>>n>>c)
{
int sum=0;
int l=strlen(c);
for(int a=0, b=0;a<l;a++)
{
while(a<=b&&b<l&&book[c[b]-'a']<n)
{
book[c[b]-'a']++;
b++;
}
sum=max(sum,b-a);
book[c[a]-'a']--;
}
cout<<sum<<endl;
}
}