#include <iostream> #include <cstdio> #include <string.h> using namespace std; void kmpGetNext(const char *p,int *b) { int i=0, j=-1; b[i]=j; int m=strlen(p); while (i<m) { while (j>=0 && p[i]!=p[j]) j=b[j]; i++; j++; b[i]=j; } for(i=0;i<=m;i++){ printf("%d ",b[i]); }cout<<endl; } void report(const char *t,int x,int m){ for(int i=x;i<x+m;++i){ printf("%c",t[i]); } cout<<endl; } void kmpSearch(const char *t,const char *p,int *b) { int i=0, j=0; int n=strlen(t),m=strlen(p);; while (i<n) { while (j>=0 && t[i]!=p[j]) j=b[j]; i++; j++; if (j==m) { report(t,i-j,m); j=b[j]; } } } int main() { // cin>>t; // cin>>p; char t[100]="aaaaababcdeeeeababcdee"; char p[100]="ababcde"; int b[100]; kmpGetNext(p,b); kmpSearch(t,p,b); return 0; }
KMP
最新推荐文章于 2023-01-23 18:57:44 发布