KMP算法

KMP算法的预处理时间为最坏情况下O(m),匹配时间是O(n),

这里重点掌握模式P的前缀函数:

next:{0,1,2,...,m-1}--->{-1,0,...,m-2} 满足 next[q]=max{k;k<q && pk+1后缀于pq}

其中pk+1是模式的前k+1个字符,pq是模式的前q个字符,

next[q]是pq的真后缀,P的最长前缀的长度。

代码:

View Code
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string>
 4 using namespace std;
 5 const int maxnum=200;
 6 int next[maxnum];
 7 string p,t;
 8 
 9 void Init()
10 {
11     int m=p.size();
12     next[0]=-1;
13     int k=-1;
14     int q;
15     for(q=1;q<m;q++)
16     {
17         while(k>-1 && p[k+1]!=p[q])
18             k=next[k];
19         if(p[k+1]==p[q])
20             k++;
21         next[q]=k;
22     }
23 }
24 
25 void KMP()
26 {
27     int n=t.size();
28     int m=p.size();
29     int q=-1;
30     int i;
31     for(i=0;i<n;i++)
32     {
33         while(q>-1 && p[q+1]!=t[i])
34             q=next[q];   //找出当前t[t]之前能成功匹配几个字符
35         if(p[q+1]==t[i])
36             q++;
37         if(q==m-1)
38         {
39             printf("start at %d\n",i+1-m); //从0开始数
40             q=next[q];
41         }
42     }
43 }
44 
45 int main()
46 {
47     cin>>p>>t;
48     Init();   //compute next[]
49     KMP();
50     return 0;
51 }
52 
53 /*
54 ababababca abacababababcabc
55 */

 poj3461 裸KMP

posted @ 2012-08-16 10:30  pushing my way  阅读(188)  评论(0编辑  收藏  举报