kmp算法

来源:互联网 发布:华联期货软件 编辑:程序博客网 时间:2024/06/05 02:56
#define MAX 10000void getNext(char *p,int next[]){    int p_len=strlen(p);    next[0]=-1;    next[1]=0;    for (int i=2;i<p_len;i++){        int q=next[i-1];        while (q!=0 && p[q]!=p[i-1])            q=next[q];        if (p[q]==p[i-1])            q++;        next[i]=q;    }    for (int i=1;i<p_len;i++){        int q=next[i];        while (q!=-1 && p[q]==p[i])            q=next[q];        next[i]=q;    }}void kmpMatch(char *p,char *t){    int next[MAX];    int p_len=strlen(p);    int t_len=strlen(t);    getNext(p,next);    int q=-1;    for (int i=0;i<t_len;i++){        q++;        while (q!=-1 && t[i]!=p[q])            q=next[q];        if (q==p_len-1)            printf("%d ",i-p_len+1);    }}