KMP 代码 暂存

#include <stdio.h>
#include <string.h>

char A[100],B[100];
int next[100];
int n, m;
void _next(){
    int i = 1;
    int j = 0;
    next[1] = 0;
    while(i<=m){
        if(j==0 || B[i-1] == B[j-1] ){++i;++j;next[i] = j;}
        else j = next[j];
    }
}

int KMP(){
    int i = 1;
    int j = 1;
    while(i<=n && j<= m){
        if(j==0 || A[i-1] == B[j-1]){++i;++j;}
        else j = next[j];
    }
    if(j>m) return i-m;
    else return -1;
}

int main(int argc, char const *argv[])
{
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%s", B);
        scanf("%s", A);
        n = strlen(A);
        m = strlen(B);
        _next();
        int i;
        for(i=1;i<=m;++i)
            printf("%d ", next[i]);
        int value = KMP();
        printf("\n%d\n", value);
    }
    return 0;
}

 

posted @ 2013-10-15 20:54  Levi.duan  阅读(166)  评论(0编辑  收藏  举报