String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1977 Accepted Submission(s): 638
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
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5672
题意:给定一个字符串和一个k,统计有多少个连续区间内不同字符数大于等于k。
解题思路:尺取法,如果下标s——t(t为第一个从s出发满足条件的下标)满足条件,那么t往后的下标都满足,再将左区间往后挪一,继续判断。
AC代码:
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
const int LEN = 1000000 + 10;//输入字符串的最长长度
int k;
char str[LEN];
void solve()
{
int s,t;
int num;//统计查找区间不同字符的个数
long long cnt;//定义为long long型,因为字符串长度有1000000
int n;
n=strlen(str);//字符串的长度
s=0,t=0;
num=0,cnt=0;
map<char,int> count;//声明map用来记录每个字符出现的次数
for(;;)//核心算法 ,尺取法
{
while(t<n&&num<k)//当下标小于字符穿长度,且区间中不同字符数小于k时循环
{
if(count[str[t++]]++==0)//出现新字符
{
num++;
}
}
if(num<k) break;//当查找区间内不同字符数小于k也即t到达字符串末尾时跳出循环
cnt+=n+1-t;//更新cnt,下标t满足条件,那么t往后的都满足
if(--count[str[s]]==0) num--;//判断左区间字符出现的次数
s++;//将左区间往后挪一
}
printf("%lld\n",cnt);
}
int main(void)
{
int T;//测试组数
scanf("%d",&T);
while(T--)
{
getchar();
scanf("%s%d",str,&k);
solve();
}
return 0;
}