题目链接:hdu1381
第一次做hash题目,看的别人的思路,先将字符串传为数学,然后每一段数字(长度为n)转换为m进制的数,再判断是否重复
#include<stdio.h>
#include<string.h>
#define N 16000005
char a[N];
int cnt[N];
int hash[8000000],d[28];
int ans,n,m;
void hashs()
{
int i,j,k = 0;
int len = strlen(a);
memset(d,0,sizeof(d));
for(i = 0 ; i < len ; i ++)
cnt[i] = a[i] - 'a';
i = 0 ;
while(i < len)
{
if(!d[cnt[i]]) d[cnt[i]] = k++;
if(k == m) break;
i ++;
}
int limit = len - n + 1;
ans = limit;//最多有多少段字符串
for(i = 0 ; i < limit ; i ++)
{
int sum = 0 ;
for(j = i ; j < i + n ; j ++)
{
sum = sum*m + d[cnt[j]];//转化为m进制的数
}
sum %= N;
if(!hash[sum])
hash[sum] = 1;
else//重复,总个数减一
ans --;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
scanf("%s",a);
memset(hash,0,sizeof(hash));
hashs();
printf("%d\n",ans);
if(T) printf("\n");
}
return 0;
}