D - String

题目

There is a string SS.SS only contain lower case English character.(10 \leq length(S) \leq 1,000,000)(10≤length(S)≤1,000,000)
How many substrings there are that contain at least k(1 \leq k \leq 26)k(1≤k≤26) distinct characters?
Input
There are multiple test cases. The first line of input contains an integer T (1\leq T\leq 10)T(1≤T≤10) indicating the number of test cases. For each test case:

The first line contains string SS.
The second line contains a integer k(1 \leq k \leq 26)k(1≤k≤26).
Output
For each test case, output the number of substrings that contain at least kk dictinct characters.
Sample
Inputcopy Outputcopy
2
abcabcabca
4
abcabcabcabc
3
0
55

思路

首先,我们准备一个起点和一个终点来表示当前字符串,在准备一个数组flag来表示字母出现了几次,用cnt表示当前字符串中出现的字母种类,当每一次flag[n]==1时,字母种类加一;当字母种类达到要求的种类时,对当前起点的字串数量进行加和,数量为字符串长度-当前字串终点位置+1,然后起点加一,并且对字母出现次数和种类进行更新;直到起点遍历完,或者终点超出界限时停止,得出答案。

代码

#include <stdio.h>
#include<string.h>
char s[10000500];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--){
		scanf("%s",s);
		int flag[30]={0};
		int len=strlen(s);
		int l=0,r=0,k;
		long long int ans=0;
		scanf("%d",&k);
		int cnt=0;
		while(l<=r&&l<len){
			while(cnt<k&&r<len){
				flag[s[r]-'a']++;
				if(flag[s[r]-'a']==1){
					cnt++;
				}
				r++;
			}
			if(cnt==k){
				ans+=len-r+1;
			}
			if(flag[s[l]-'a']==1){
				cnt--;
			}
			flag[s[l]-'a']--;
			l++;
		}
		printf("%lld\n",ans);	
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漠–

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值