KMP算法

  关于KMP入门,可以参考:KMP入门

  另外附上我自己的KMP代码:

  

#include <cstring>
#include <iostream>
#include <cstdio>
using namespace std;
const int MAXL = 1000001;

char s1[MAXL], s2[MAXL];
int la, lb;
int next[MAXL];

void clcNext() {
    next[0] = -1;
    int j = 0;
    int k = -1;
    while(j < la) {
        if((k == -1) || (s2[j] == s2[k])) {
            next[++j] = ++k;
        } else {
            k = next[k];
        }
    }
}

void KMP() {
    int i = 0;
    int j = 0;
    while(i < la) {
        if((j == -1) || (s1[i] == s2[j])) {
            i++;
            j++;
        } else {
            j = next[j];
        }
        if(j == lb) {
            printf("%d\n", i - j + 1);
        }
    }
}

int main() {
    scanf("%s%s", s1, s2);
    la = strlen(s1);
    lb = strlen(s2);
    clcNext();
    KMP();
    for(int i = 1; i <= lb; i++) {
        printf("%d ", next[i]);
    }
    return 0;
}

 

 

  圆满完成。

posted @ 2018-09-05 04:11  potato226  阅读(119)  评论(0编辑  收藏  举报