原题链接
There is a string S.S only contain lower case English character.(10≤length(S)≤1,000,000)
How many substrings there are that contain at least k(1≤k≤26) distinct characters?
Input
There are multiple test cases. The first line of input contains an integer T(1≤T≤10) indicating the number of test cases. For each test case:
The first line contains string S.
The second line contains a integer k(1≤k≤26).
Output
For each test case, output the number of substrings that contain at least k dictinct characters.
Sample Input
2
abcabcabca
4
abcabcabcabc
3
Sample Output
0
55
题目描述
在给定的一串字符中,有子序列有k个不同的字符,求这样子序列至少存在多少个
思路:(尺取)对字符串进行处理,记录一个区间不同字符的个数,本来使用map但总是超时,所以就用一个数组来判断不同的字符
代码如下
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char s[1000005];
int main()
{
int i,j,t,k,num,n;//num用来记录区间不同字符的个数
long long ans;//记录满足条件的子序列数量
int m[26];//记录每个字符出现的次数
scanf("%d",&t);
while(t--)
{
memset(m, 0, sizeof(m));
scanf("%s",s);
n = strlen(s);
scanf("%d",&k);
i = j = num = ans = 0;
while(1)
{
//循环找出区间恰好num == k的区间
while(j < n && num < k)
{
//如果这字符是新出现的,那么num++
if(m[s[j]-'a'] == 0)
num++;
m[s[j]-'a']++;
j++;
}
if(num < k)
break;
//那么后面的字符加入该序列都可以满足条件
ans += n - j + 1;
m[s[i]-'a']--;
//当该区间的最后一个去掉之后,如果对应的字符数量变为0,那么num--
if(m[s[i]-'a'] == 0)
num--;
i++;
}
printf("%lld\n",ans);
}
return 0;
}