KMP模板

来源:互联网 发布:linux open 返回值 编辑:程序博客网 时间:2024/06/08 02:29

KMP主要就是对每次移动的位置进行了优化

移动位数=当前失配前匹配的长度减去最大前缀后缀重叠长度


模板

#include<bits/stdc++.h>void makeNext(const char P[],int next[])  {    int q,k;    int m = strlen(P);    next[0] = 0;    for (q = 1,k = 0; q < m; ++q) {        while(k > 0 && P[q] != P[k])            k = next[k-1];        if (P[q] == P[k]) {            k++;        }        next[q] = k;    }}int kmp(const char T[],const char P[],int next[])  {    int n,m;    int i,q;    n = strlen(T);    m = strlen(P);    makeNext(P,next);    for (i = 0,q = 0; i < n; ++i) {        while(q > 0 && P[q] != T[i])            q = next[q-1];        if (P[q] == T[i]) {            q++;        }        if (q == m) {            printf("匹配下标为",(i-m+1));        }    }}int main(){    int i;    int next[20]={0};    char T[] = "abaccccc";    char P[] = "acc";    printf("%s\n",T);    printf("%s\n",P );    kmp(T,P,next);    return 0;}


0 0
原创粉丝点击