POJ1200 Crazy Search(hash)

题意:

给一个有nc种字符的字符串,要求它有几个大小为n的子串。

要点:

字符串长度可以是16000000但字符总数最多300,所以hash是必不可少的。先将nc种字符一一对应到hash数组中,只存入第一次出现的位置,使每一个字符都对应这0---nc-1的一个数字,然后是重点:将长度为n的子串看作n位的nc进制数,将问题转化为共有多少种十进制数字,用数组记录,最后遍历子串即可。


15453196 Seasonal 1200 Accepted 16512K 32MS C++ 686B 2016-04-30 09:19:00
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 16000001
char str[maxn];
bool array[maxn];	//看子串是否已经出现过
int hash[300];		//字符最多也就300个

int main()
{
	int n, nc,i,j;
	while (scanf("%d%d", &n, &nc) != EOF)
	{
		memset(array, false, sizeof(array));
		memset(hash, 0, sizeof(hash));
		scanf("%s", str);
		int len = strlen(str),count=0;
		for (i = 0; i < len; i++)
			if (hash[str[i]] == 0)
				hash[str[i]] = ++count;//利用hash将字符串中的字符映射到数组对应下标中,重复的只要取第一个即可
		int res = 0;
		for (i = 0; i+n <= len; i++)
		{
			int sum = 0;
			for (j = i; j < i + n; j++)
			{
				sum *= nc;
				sum += hash[str[j]];//将nc视为nc进制,转换为对应的十进制看是否出现过
			}
			if (!array[sum])
			{
				array[sum] = true;
				res++;
			}
		}
		printf("%d\n", res);
	}
	return 0;
}


posted @ 2016-04-30 09:28  seasonal  阅读(95)  评论(0编辑  收藏  举报