kmp算法学习(未完成)

来源:互联网 发布:中国煤炭进口量数据 编辑:程序博客网 时间:2024/05/18 02:07

例如

#include <cstdio>#include <algorithm>#include <cstring>using namespace std;void get_next(char *t, int *next){    int j = 0, i = 1;    int len = strlen(t);    next[1] = 0;    while(i <= t[0])    {        if(j == 0 || t[i] == t[j])        {            i++;            j++;            next[i] = j;        }        else        {            j = next[j];        }    }}int kmp(char *s, char *t, int pos){    int i = pos;    int j = 1;    int next[10100];    get_next(t, next);    for(int k = 1; k < t[0]; k++)        printf("%d ", next[k]);    printf("%d\n", next[t[0]]);    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];    return 0;}int main(){    char s[10100], t[10100];    int next[10100];    while(scanf("%s %s", s+1, t+1) != EOF)    {        s[0] = strlen(s+1);        t[0] = strlen(t+1);        get_next(t, next);        printf("%d\n", kmp(s, t, 0));    }    return 0;}


总结


原创粉丝点击