题目
There is a string SS.SS only contain lower case English character.(10 \leq length(S) \leq 1,000,000)(10≤length(S)≤1,000,000)
How many substrings there are that contain at least k(1 \leq k \leq 26)k(1≤k≤26) distinct characters?
Input
There are multiple test cases. The first line of input contains an integer T (1\leq T\leq 10)T(1≤T≤10) indicating the number of test cases. For each test case:
The first line contains string SS.
The second line contains a integer k(1 \leq k \leq 26)k(1≤k≤26).
Output
For each test case, output the number of substrings that contain at least kk dictinct characters.
Sample
Inputcopy Outputcopy
2
abcabcabca
4
abcabcabcabc
3
0
55
思路
首先,我们准备一个起点和一个终点来表示当前字符串,在准备一个数组flag来表示字母出现了几次,用cnt表示当前字符串中出现的字母种类,当每一次flag[n]==1时,字母种类加一;当字母种类达到要求的种类时,对当前起点的字串数量进行加和,数量为字符串长度-当前字串终点位置+1,然后起点加一,并且对字母出现次数和种类进行更新;直到起点遍历完,或者终点超出界限时停止,得出答案。
代码
#include <stdio.h>
#include<string.h>
char s[10000500];
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%s",s);
int flag[30]={0};
int len=strlen(s);
int l=0,r=0,k;
long long int ans=0;
scanf("%d",&k);
int cnt=0;
while(l<=r&&l<len){
while(cnt<k&&r<len){
flag[s[r]-'a']++;
if(flag[s[r]-'a']==1){
cnt++;
}
r++;
}
if(cnt==k){
ans+=len-r+1;
}
if(flag[s[l]-'a']==1){
cnt--;
}
flag[s[l]-'a']--;
l++;
}
printf("%lld\n",ans);
}
}