KMP

 1 /**************************************************
 2           Target: kmp function
 3           Author: Xue Zhonghao
 4           Date: 2014-2-28 19:28:17 
 5 **************************************************/ 
 6 
 7 #include<cstdio>
 8 #include<cstdlib>
 9 #include<string>
10 #include<iostream>
11 using namespace std;
12 
13 #define max_length 2000
14 
15 void getFail(string a, int *f)//失配函数 
16 {
17     int m = a.length();
18     f[0] = 0, f[1] = 0;//递推边界初值 
19     for(int i = 0; i < m; i++){
20         int j = f[i];
21         while(j && a[i]!=a[j]) j = f[j];
22         f[i+1] = (a[i]==a[j])?(j+1):(0);
23     }
24 }
25 
26 int kmp(string a, string b, int *f)
27 {
28     int n = a.length(), m = b.length();
29     getFail(b, f);
30     int j = 0;                             //当前节点编号 
31     for(int i = 0; i < n; i++){            //模板当前指针 
32         while(j && a[i]!=b[j]) j = f[j];   //顺失配边寻找匹配(到0为止) 
33         if(a[i] == b[j]) ++j;
34         if(j == m) return i-m;             //输出 
35     }
36     return -1;
37 }
38 
39 int main(void)
40 {
41     string a, b;//a模板,b子串 
42     int ans;
43     int f[max_length];
44     cin>>a>>b;
45     ans = kmp(a, b, f);//kmp函数,返回子串第一次在模板中出现的位置,若没有答案返回-1 
46     if(ans == -1) cout<<"NO ANSWER"<<endl;
47     else cout<<ans<<endl;
48     system("pause");
49     return 0;
50 }

 

posted on 2014-04-07 16:52  AlanXue  阅读(158)  评论(0编辑  收藏  举报

导航