There is a string 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
題目大意: 給最長1e6的字符串和k,讓你求有多少個子串,每個子串至少包含k個不同的字符。
思路: 尺取:既然讓找的每個子串至少包含k個不同的字符,就設兩個變量 l和r,從頭開始,固定 l,r後移,直到有出現k個不同的子串停止,則 r及右端點後面的不影響該子串,所以從 l開始的滿足要求的子串有 n-r+1個,如此遍歷每個左端點;
小優化:將沒出現過的字符標記一下,出現過則不統計,這樣r就可以不用一直從1開始。
ac代碼
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e6+7;
const ll INF=1e9+7;
ll n;
char c[maxn];
ll vis[maxn];
int main()
{
ll t;
scanf("%lld",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
scanf("%s",c);
scanf("%lld",&n);
ll l=0,r=0;
ll len=strlen(c);
ll k=0,ans=0;
while(l<len)
{
//r=l;
while(r<len&&k<n)
{
if(vis[c[r]-'a']==0)
k++;
vis[c[r]-'a']++;
r++;
}
if(k<n) //如果剩下的不同字符少於最少要滿足的個數,退出
break;
ans+=len-r+1;
vis[c[l]-'a']--;
if(vis[c[l]-'a']==0)
k--;
l++;
}
printf("%lld\n",ans);
}
return 0;
}