KMP

来源:互联网 发布:淘宝买iphone7 店铺 编辑:程序博客网 时间:2024/05/19 19:34
#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;}


	
				
		
原创粉丝点击