1. 程式人生 > >字符串算法hash

字符串算法hash

closed 處理 cst dia nbsp span using str 初始

思路:給字符串做一個映射,兩個元素相同,則他們的hash值必定相同。

例題:

Description

給出兩個字符串W和T,求T中有幾個W子串。

Input

第一行為數據數.

每組數據有兩行W和T,表示模式串和原始串.

Output

對每組數據,每行一個數,表示匹配數.

Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN
Sample Output

1
3
0

代碼:

技術分享圖片
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace
std; const int maxn = 1200; typedef unsigned long long ULL; ULL pre[maxn],hs[maxn],base=133; //base基數設置為素數 char s1[maxn],s2[maxn]; void Init() { pre[0]=1; for(int i=1;i<maxn;i++) pre[i]=pre[i-1]*base; } ULL getl(int l,int r) { return hs[r]-hs[l-1]*pre[r-l+1]; } int main(void) { int
T,i; scanf("%d",&T); Init(); //初始化pre數組,記錄n個數的base值 while(T--) { scanf("%s%s",s1+1,s2+1); int l1=strlen(s1+1),l2=strlen(s2+1),ans=0; ULL a1=0; for(i=1;i<=l1;i++) a1=a1*base+(ULL)s1[i]; //處理子串 for(hs[0]=0,i=1;i<=l2;i++) hs[i]=hs[i-1]*base+(ULL)s2[i]; //
處理主串 for(i=1;i+l1-1<=l2;i++) if(a1==getl(i,i+l1-1)) ans++; //統計主串中的子串。 printf("%d\n",ans); } return 0; }
View Code

字符串算法hash