String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1077 Accepted Submission(s): 348
Problem Description
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?
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) .
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
Source
题意:给出一串字符串,再给出一个k,求出有多少个子串满足有k种及以上不同的字符。
思路:设置两个指针,st代表子串的最左端,ed代表子串的最右端。在移动过程中,如果st-ed之间的字符少于k,那么ed就向右移动,直到st-ed之间的字符等于k,然后通过num数组计算出包含st-ed这个区间的子串的个数。st指针则每次保证移动一步。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[1000005];
int num[30];//计数当前区间内每个字母的个数
int main(){
int cases,i,j,k,len,cnt,st,ed;
cin>>cases;
while(cases--){
long long ans=0;
memset(num,0,sizeof(num));
scanf("%s",s+1);//起点为s[1]
len=strlen(s+1);
cin>>k;
st=0;
ed=0;
cnt=0;
for(st=1;st<=len;st++){
while(cnt<k && ed<len){//当区间内不同字符个数小于k且ed不越界
ed++;//ed向后走
num[s[ed]-'a']++;//ed指针指向的字符加入区间中,并计数
if(num[s[ed]-'a']==1)cnt++;//如果遇到一个字符当前计数为第一次,则说明遇到了不同的字符
}
if(cnt==k){//加上包含该区间的子串
ans+=len-ed+1;
}
num[s[st]-'a']--;
if(num[s[st]-'a']==0)cnt--;
}
cout<<ans<<endl;
}
return 0;