KMP算法

来源:互联网 发布:怎么看淘宝卖家淘金币 编辑:程序博客网 时间:2024/04/30 19:48

下面的程序对next生成算法进行了优化,比前面的方法快。

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

int index_kmp(char S[ ], char T[ ], int next[])
{    
    int i, j, S_len = strlen(S), T_len = strlen(T);
    i = j = 0;
    while (i < S_len && j < T_len) {
        if (j == -1 || S[ i ] == T[ j ]) { i++; j++;}
        else { j = next[ j ]; }
    }
    if (j == T_len) return (i - T_len);
    return -1;
}

void get_next(char T[ ], int next[])
{    
    int i, j, T_len = strlen(T);
    i = 0; j = -1;
    next[0] = -1;
    while (i < T_len - 1) {
        if (j == -1 || T[ i ] == T[ j ]) {
            i++; j++;
            if (T[ i ] == T[ j ])
                next[ i ] = next[ j ];
            else
                next[ i ] = j;
        }
        else j = next[ j ];
    }
}

#define MAX_SIZE 256

int main()
{
    char szMain[MAX_SIZE];
    char szSub[MAX_SIZE];
    int i, iIndex, iSubLen, aiNext[MAX_SIZE];
    printf("input main string:/n");
    scanf("%255s", szMain);
    printf("input sub string:/n");
    scanf("%255s", szSub);
    get_next(szSub, aiNext);
    iSubLen = strlen(szSub);
    printf("next[]: ");
    for (i = 0; i < iSubLen; i++)
    {
        printf("%d ", aiNext[i]);
    }
    printf("/n");
    iIndex = index_kmp(szMain, szSub, aiNext);
    printf("index = %d/n", iIndex);

    fgets(szMain, MAX_SIZE, stdin);
    getchar();
    return 0;
}

原创粉丝点击