KMP算法

来源:互联网 发布:东方project知乎 编辑:程序博客网 时间:2024/06/06 05:40
#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAXN 255typedef  char SString[MAXN + 1];int next[1 << 8];void get_nextval(SString t) {    int i = 1, j = 0;    next [1] = 0;     while (i < t[0]) {        if (j == 0 || t[i] == t[j]) {            ++i; ++j;            if (t[i] != t[j]) next[i] = j;            else next[i] = next[j];        }        else j = next[j];    }    for (int h = 1; h <= i; ++h) {        printf("%d", next[h]);    }    puts("");}int Index_KMP(SString s, SString t) {    get_nextval(t);    int i = 0, j = 1;    while (i <= s[0] && j <= t[0]) {        if (j == 0 || s[i] == t[j]) {++i; ++j;}        else j = next[j];    }    if (j > t[0]) return i - t[0];    else return 0;}int main() {    SString s, t;    strcpy(s, " aadabbadada"); strcpy(t, " adabbadada");    s[0] = strlen(s) - 1; t[0] = strlen(t) - 1;    printf("%d\n", Index_KMP(s, t));    return 0;}

原创粉丝点击