KMP模式匹配算法

来源:互联网 发布:什么是数据api接口 编辑:程序博客网 时间:2024/06/10 06:13

首先,这是由Knuth、Morris和Prattle三人设计的线性时间字符串匹配算法。
这里就不仔细的讲解,网上有更好的讲解,在这推荐几个自己当时学习的KMP所看到的较好理解的

  1. http://www.cnblogs.com/c-cloud/p/3224788.html
  2. http://www.61mon.com/index.php/archives/183/

这里附上自己所学的代码:

#include<bits/stdc++.h> using namespace std;/*s[]:是主串p[]:是模式串*/int next[10000];void getNext(char *s){    int i,j;    i = 0;    j = next[0] = -1;    int s_len = strlen(s);    while(i<s_len){        while(j!=-1&&s[i]!=s[j]){            j = next[j];        }        next[++i] = ++j;    }}int KMP(char *s,char *p){    int s_len = strlen(s);    int p_len = strlen(p);    int i,j,ans;    getNext(p);    i = ans = j =0;    while(i<s_len){        while(j!=-1&&p[j]!=s[i]){            j = next[j];        }        i++,j++;        if(j>=p_len){            ans++;            j = next[j];            printf("%d\n",i-1);  //输出p[]所在的位置         }    }    return ans;  //返回p[]在s[]中出现的次数 }int main(){    char s[] = "abababab";    char p[] = "aba";    printf("%d\n",KMP(s,p));     return 0;}