KMP

KMP是一种改进的字符串匹配算法,我现在目前为止还只会裸的。

kmp算法完成的任务是:给定两个字符串O和f,长度分别为n和m,判断f是否在O中出现,如果出现则返回出现的位置。常规方法是遍历a的每一个位置,然后从该位置开始和b进行匹配,但是这种方法的复杂度是O(nm)。kmp算法通过一个O(m)的预处理,使匹配的复杂度降为O(n+m)。

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<string>
 7 #include<vector>
 8 using namespace std;
 9 
10 const int NN=1000007;
11 
12 int len1,len2,Next[NN];
13 char s1[NN],s2[NN];
14 vector<int>ans;
15 
16 void Make_Next()
17 {
18     Next[0]=-1,Next[1]=0;
19     for (int i=2;i<=len2;i++)
20     {
21         int k=i-1;
22         while(s2[i]!=s2[Next[k]+1])
23         {
24             k=Next[k];
25             if (k==0) break;
26         }
27         Next[i]=Next[k]+1; 
28     }
29     Next[0]=0;
30 }
31 void Kmp()
32 {    
33     Make_Next();
34     int i=1,j=1;
35     while (i<=len1)
36         if (s1[i]==s2[j])
37         {
38             i++,j++;
39             if (j==len2+1)
40             {
41                 j=Next[j-1]+1;
42                 ans.push_back(i-len2);
43             }
44         }
45         else
46         {
47             if (j==1) i++;
48             j=Next[j-1]+1;
49         }
50 }
51 int main()
52 {
53     scanf("%s%s",s1+1,s2+1);
54     len1=strlen(s1+1),len2=strlen(s2+1);
55     
56     Kmp();
57     
58     for (int i=0;i<ans.size();i++)
59         printf("%d
",ans[i]);
60 }
原文地址:https://www.cnblogs.com/fengzhiyuan/p/7172286.html