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
由字符串映射到数字需要map函数,这里贴一个map函数的最入门用法,结合代码理解着看
#include<cstdio>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
string s;
int main()
{
long long k;
while(cin>>k>>s)
{
map<char,int>x;
int r,l,ans=0;
for(r=0,l=0;l<s.length();++l)
{
while(l<=r&&r<s.length()&&x[s[r]]<k)
{
x[s[r]]++;
r++;
}
ans=max(ans,r-l);
x[s[l]]--;
}
printf("%d\n",ans);
}
}