Substring

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函数的最入门用法,结合代码理解着看

https://blog.csdn.net/qq_52792570/article/details/113566757?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162730458416780269895626%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=162730458416780269895626&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-113566757.pc_search_all_es&utm_term=map%E5%87%BD%E6%95%B0&spm=1018.2226.3001.4187

#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);
	}
}

上一篇:The xor-longest Path POJ - 3764 字典树+树的遍历


下一篇:Longest Peak