string
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个不同字符的子数组的个数。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL ;
LL num = 0 ;
const int N = 1e6+100 ;
int a[N] , b[35] ;
char s[N] ;
int k ;
int main()
{
int t ;
scanf("%d" , &t) ;
while(t--)
{
scanf("%s" , s+1) ;
scanf("%d" , &k) ;
int len = strlen(s+1) ;
memset(b , 0 , sizeof(b));
for(int i = 1; i <= len ;i ++)
a[i] = s[i] - 'a' + 1 ;
int sum = 0 ;
int l = 0 ;
num = 0 ;
for(int i = 1 ;i <= len ; i ++)
{
while(l + 1 <= len && sum < k)
{
l ++ ;
b[a[l]]++ ;//记录每个字符
if(b[a[l]] == 1)
sum ++ ;
}
if(sum == k)
num += len-l+1 ;
b[a[i]]-- ; //左指针右移
if(b[a[i]]==0)
sum-- ;
}
printf("%lld\n" ,num) ;
}
return 0;
}