hdu 4821 String

本文介绍了一种使用哈希算法解决字符串中特定长度子串的唯一性问题的方法,详细解释了算法实现过程和应用实例。

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

        题意:给一个串,问存在多少个子串长度为m*l,其中m段长度为l的子子串各不相同。

        思路:哈希。将每段长度为l的子串哈希,就可以迅速比较是否相同,然后插入到map中检查。


#include <iostream>       
#include <stdio.h>       
#include <cmath>       
#include <algorithm>       
#include <iomanip>       
#include <cstdlib>       
#include <string>       
#include <string.h>       
#include <vector>       
#include <queue>       
#include <stack>       
#include <map>     
#include <set>     
#include <ctype.h>       
#include <sstream>   
#define INF 1000000000   
#define ll long long   
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
     
using namespace std;

#define maxlen 100010
#define ull unsigned long long  

char str[maxlen];

const int x=123;
ull xn[maxlen],H[maxlen],hash[maxlen];

int main(){
	xn[0]=1;
	for(int i=1;i<=100000;i++)xn[i]=xn[i-1]*x;
	int m,l;
	while(cin>>m>>l){
		scanf("%s",str);
		int siz=strlen(str);
		H[siz]=0;
		for(int i=siz-1;i>=0;i--)H[i]=H[i+1]*x+(str[i]-'a');
		
		hash[siz-l]=H[siz-l];
		for(int i=siz-l-1;i>=0;i--)hash[i]=H[i]-H[i+l]*xn[l];
		
		int ans=0;
		for(int i=0;i<l;i++){
			map<ull,int> mp;
			int cnt=0;
			for(int j=i;j+l<=siz;j+=l){
				if(j/l>=m){
					mp[hash[j-l*m]]--;
					if(mp[hash[j-l*m]]==0)mp.erase(hash[j-l*m]);
				}
				mp[hash[j]]++;
				if(mp.size()==m)ans++;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值