KMP算法实现

落花浮王杯 提交于 2019-11-26 18:31:29

算法这篇文章写得很明了: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

 

转载于:https://www.cnblogs.com/Leo-Forest/archive/2013/05/24/3066071.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!