#include <iostream>
#include <string.h>
using namespace std;
void CalNext(const char *pattern, int next[]){
int j=0;
int len = strlen(pattern);
next[0]=-1;
int k=-1;
while(j < len-1){
if((k==-1) || pattern[k] == pattern[j]){
//对啊。一直遍历嘛。所以要一直++
++k;
++j;
next[j] = k;
}else{
k = next[k];//递归
}
}
}
int KMP(int next[], const char *text, const char *pattern){
int i=0,j=0,ans=0;
int n = strlen(text);
int len = strlen(pattern);
while(i<n){
//if(j==-1 || text[i]==pattern[i]){
if(j==-1 || text[i]==pattern[j]){
++i;
++j;
}else{
j = next[j];
}
if(j==len){
ans = i-len;
break;
}
}
return ans;
}
int main()
{
int next[5];
char str[]="abcdabaabef";
char *text = "abcdabaabef";
char *pattern = "abaab";
CalNext(pattern,next);
cout<<"位置"<<KMP(next, str, pattern)<<endl;
cout<<"位置"<<KMP(next, text, pattern)<<endl;
return 0;
}
kmp算法
最新推荐文章于 2024-10-25 22:28:50 发布