KMP算法实现

算法这篇文章写得很明了:http://news.cnblogs.com/n/176771/

以下是实现:

KMP.cc

#include        <iostream>
#include        <cstring>
#include        <cstdlib>

// Calc partition table
void mkRpTab(const char* str, int* tab, int len)
{
    for (int i=0; i<len; ++i) {
        int j = i;
        for(; j>0; --j) {
            if (strncmp(str, str+i-j+1, j) == 0)
                break;
        }
        tab[i] = j;
        std::cout << tab[i] << "  ";
    }
    std::cout << std::endl;
}
// kmp
void kmp()
{
    const char* meterial = "BBC ABCDAB ABCDABCDABDE";
    const char* keyStr = "ABCDABD";
    std::cout << "meterial: " << meterial << std::endl;
    std::cout << "keyStr: "   << keyStr << std::endl;
    int* tab = (int *) malloc(sizeof(int) * strlen(keyStr));;
    mkRpTab(keyStr, tab, strlen(keyStr));


    int meterialLen = strlen(meterial);
    int keyLen = strlen(keyStr);
    int meterialOffset = 0;
    int keyOffset = 0;

    while (meterialOffset < meterialLen) {
        if (meterial[meterialOffset] == keyStr[keyOffset]) {
            if (keyOffset < keyLen - 1) {
                ++meterialOffset;
                ++keyOffset;
            } else {
                std::cout << "matched: " << meterialOffset - keyLen + 1 << std::endl;
                keyOffset = 0;
                ++meterialOffset;
            }
        } else {
            if (keyOffset == 0) {
                ++meterialOffset;
            } else {
                meterialOffset += (keyOffset - tab[keyOffset - 1]);
                keyOffset = 0;
            }
        }
    }

    free(tab);
}


// ===  FUNCTION  ======================================================================
//         Name:  main
//  Description:  main function
// =====================================================================================
        int
main ( int argc, char *argv[] )
{
    kmp();
        return EXIT_SUCCESS;
}               // ----------  end of function main  ----------

结果:

root >>> ./a.out
meterial: BBC ABCDAB ABCDABCDABDE
keyStr: ABCDABD
0  0  0  0  1  2  0
matched: 15

 

posted @ 2013-05-24 23:08  Leo Forest  阅读(194)  评论(0编辑  收藏  举报