首先,这是由Knuth、Morris和Prattle三人设计的线性时间字符串匹配算法。
这里就不仔细的讲解,网上有更好的讲解,在这推荐几个自己当时学习的KMP所看到的较好理解的
- http://www.cnblogs.com/c-cloud/p/3224788.html
- http://www.61mon.com/index.php/archives/183/
这里附上自己所学的代码:
#include<bits/stdc++.h>
using namespace std;
/*
s[]:是主串
p[]:是模式串
*/
int next[10000];
void getNext(char *s){
int i,j;
i = 0;
j = next[0] = -1;
int s_len = strlen(s);
while(i<s_len){
while(j!=-1&&s[i]!=s[j]){
j = next[j];
}
next[++i] = ++j;
}
}
int KMP(char *s,char *p){
int s_len = strlen(s);
int p_len = strlen(p);
int i,j,ans;
getNext(p);
i = ans = j =0;
while(i<s_len){
while(j!=-1&&p[j]!=s[i]){
j = next[j];
}
i++,j++;
if(j>=p_len){
ans++;
j = next[j];
printf("%d\n",i-1); //输出p[]所在的位置
}
}
return ans; //返回p[]在s[]中出现的次数
}
int main(){
char s[] = "abababab";
char p[] = "aba";
printf("%d\n",KMP(s,p));
return 0;
}
本文介绍了由Knuth、Morris和Pratt设计的KMP线性时间字符串匹配算法,并提供了详细的C++实现代码。通过两个推荐的学习资源链接,读者可以更深入地理解KMP算法的工作原理。
557

被折叠的 条评论
为什么被折叠?



