首页 > 编程语言 > 详细

KMP C++

时间:2017-10-07 23:23:03      阅读:248      评论:0      收藏:0      [点我收藏+]

KMP C++实现

int * ComputeNext(string P)
{
    int *lsp{ new int[P.length()] };

    lsp[0] = 0;  // Base case
    int j = 0;

    for (int i = 1; i < P.length(); i++)
    {//        int j = lsp[i - 1];
        while (j > 0 && P.at(i) != P.at(j))
            j = lsp[j];

        if (P.at(i) == P.at(j))
            j++;

        lsp[i] = j;
    }
    return lsp;
}

int search(string P, string T)
{
    int *lsp= ComputeNext(P);

    for (int var = 0; var < P.length(); var++)
    {
        cout << *(lsp+var) << " ";
    }
    cout<<endl;
    int j = 0;                                

    for (int i = 0; i < T.length(); i++)
    {
        while (j > 0 && T.at(i)!= P.at(j))
        {                                    
            j = *(lsp+j);                    
            cout<<"-i:"<<j<<endl;
        }
        cout<<i<<" "<<T.at(i)<<","<<j<<" "<<P.at(j)<<"|| ";
        if (T.at(i) == P.at(j))
        {
            j++;

            if (j == P.length())
                return (i -P.length()+1) ;

            cout<<T.at(i)<<","<<P.at(j)<<":";
        }

        cout<<i<<"-"<<j<<endl;

    }
    delete []lsp;
    return -1;        
}

 

KMP C++

原文:http://www.cnblogs.com/yunqie/p/7636073.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!