KMP超强模板贴一份

while(scanf("%s",str+1)==1 ) {
        int n=strlen(str+1);
        next[1]=0int j=0;
        for(int i=2;i<=n;i++) {
            while(j&&str[j+1]!=str[i]) j=next[j];
            if(str[i]==str[j+1]) j++;
            next[i]=j;
        }
        for(int i=1;i<=n;i++) printf("%d ",next[i]);

 

 随便给出一个字符串  对应的next数组为

 A B R A C D A B R A

 0 0 0 1 0 1 0 2 3 4

 其实就是找前缀了拉

 

 模式匹配代码贴一份。

 

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <vector>
 6 #include <list>
 7 #include <queue>
 8 using namespace std;
 9 const int MAX = 1e6+10;
10 const int inf = 0x3f3f3f3f;
11 char str1[MAX],str2[MAX];
12 int next[MAX];
13 int main()
14 {
15     //freopen("in","r",stdin);
16     //freopen("out","w",stdout);
17     int cas;
18     scanf("%d",&cas);
19     while(cas--) {
20         scanf("%s %s",str1+1,str2+1);
21         int n=strlen(str1+1);
22         next[1]=0int j=0;
23         for(int i=2;i<=n;i++) {
24             if(j&&str1[i]!=str1[j+1]) j=next[j];
25             if(str1[i]==str1[j+1]) j++;
26             next[i]=j;
27         }
28         int ans=0;
29         int len=strlen(str2+1); j=0;
30         for(int i=1;i<=len;i++) {
31             while(j&&str2[i]!=str1[j+1]) j=next[j];
32             if(str2[i]==str1[j+1]) j++;
33             if(j==n) ans++;
34 
35         }
36         printf("%d\n",ans);
37 
38     }
39 
40     return 0;
41 }

 

 

posted @ 2014-05-16 20:04  acvc  阅读(192)  评论(0编辑  收藏  举报