HDU 5672 String

本文介绍了一道关于字符串的编程题,旨在统计给定字符串中包含至少k种不同字符的所有子串数量。通过使用尺取法进行高效求解,并提供了详细的解题思路与AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. (10length(S)1,000,000)
How many substrings there are that contain at least  k(1k26)  distinct characters?
 

Input
There are multiple test cases. The first line of input contains an integer  T(1T10)  indicating the number of test cases. For each test case:

The first line contains string  S .
The second line contains a integer  k(1k26) .
 

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值