poj1200_经典hash

题意:给出两个数n,nc,并给出一个由nc种字符组成的字符串。求这个字符串中长度为n的子串有多少种。

分析:

1.这个题不用匹配,因为不高效。

2.将长度为n的子串看作n位的nc进制数,将问题转化为共有多少种十进制数字。

3.哈希时,每一个字符都对应这0---nc-1的一个数字。

代码:

View Code
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <memory.h>
 4 using namespace std;
 5 const int maxnum=1600000;
 6 char str[maxnum];
 7 bool array[20000000];
 8 int hash[256];
 9 
10 int main()
11 {
12     int n,nc;
13     int i,cnt,len,sum,j,res;
14     while(scanf("%d%d%s",&n,&nc,str)!=EOF)
15     {
16         cnt=0;
17         memset(hash,0,sizeof(hash));
18         memset(array,false,sizeof(array));
19         len=strlen(str);
20         for(i=0;i<len;i++)
21             if(hash[str[i]]==0)   //cnt最大为nc-1
22                 hash[str[i]]=cnt++;
23         res=0;
24         for(i=0;i+n<=len;i++)
25         {
26             sum=0;
27             for(j=i;j<i+n;j++)
28             {
29                 sum*=nc;   //将长度为n的子串看作是n位nc进制数,这里求的是这个n为nc进制数的对应的十进制数。
30                 sum+=hash[str[j]];
31             }
32             if(!array[sum])
33             {
34                 res++;
35                 array[sum]=true;
36             }
37         }
38         printf("%d\n",res);
39     }
40     return 0;
41 }

tju oj1663

posted @ 2012-08-15 12:38  pushing my way  阅读(1009)  评论(0编辑  收藏  举报