HDU 5672 String (尺取法)

本文介绍了一道编程题目,旨在统计字符串中至少包含k种不同字符的所有子串数量。通过双指针法实现高效遍历,辅以计数数组记录字符出现情况。

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

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. (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
 

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值