题意
给定一个只有小写字母字符串
,求存在多少个子串至少包含了
种子母。
思路
开一个 数组记录此时每种字母出现的次数,并用 实时记录不同字母的个数。如果右移使此字母的 值由零变成一, 值就加一;如果左移使此字母的 值由一变成零, 值就减一。右移至 时累计答案。
代码
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
char str[1000003];
int cnt[28];
int main()
{
int T,k;
scanf("%d",&T);
while(T--)
{
memset(cnt,0,sizeof(cnt));
scanf("%s%d",str+1,&k);
int n=strlen(str+1),R=0,cur=0;
LL ans=0;
FOR(L,1,n)
{
while(L>R||R<n&&cur<k)
{
if(cnt[str[++R]-'a']==0)cur++;
cnt[str[R]-'a']++;
}
if(R>n)break;
if(cur>=k)ans+=n-R+1;
cnt[str[L]-'a']--;
if(cnt[str[L]-'a']==0)cur--;
}
printf("%lld\n",ans);
}
return 0;
}