KMP

KMP

标签(空格分隔): Data-Structure


照着金叔课本来的,因为看了其他各种版本,各种混乱

8.15 普通解法

#include <iostream>
#include <cstring>

using namespace std;

//textbook, the regular solution
void getNext(const char *s, int next[])
{
    int len = strlen(s);
    int j = 1,i = -1;
    next[0] = -1;
    while(j < len){
        i = next[j-1];
        while((i>=0) && (s[j]!=s[i+1]))
            i = next[i];

        if(s[j] == s[i+1])
            next[j] = i+1;
        else
            next[j] = -1;

        j++;
    }
}

int Find(const char *s, const char *pat, int next[])
{
    int i = 0, j = 0;
    int lenS = strlen(s), lenP = strlen(pat);
    cout<<lenS<<" "<<lenP<<endl;
    while((j < lenP) && (i < lenS)){//bug 写成了 i < lenS - lenP + 1
        if(s[i] == pat[j]){
            i++;
            j++;
        }
        else if(j == 0)
            i++;
        else{
            j = next[j-1] + 1;
        }
    }
    if(j <lenP || lenP == 0)
        return -1;
    else
        return (i - lenP);//完全匹配后 i 位于母串中子串序列的最后一个下标+1的位置

}
/* another book, tend to abandon
//void getNext(const char *s, int next[])
//{
//    int i = 0, j= -1;
//    next[0] = -1;
//    int len = strlen(s);
//    while(i < len){
//        if(j == -1 || s[i] == s[j])
//        {
//            ++i;
//            ++j;
//            next[i] = j;
//        }
//        else
//            j = next[j];
//    }
//} */
int main()
{
    const char *pat = "abcabcacab";
    const char *s = "abcdabceabcabcacab";
    int lengthP = strlen(s);
    //cout<<length<<endl;
    int next[lengthP];
    for(int i = 0; i<lengthP; i++)
    {
        next[i]=0;
        //cout<<next[i]<<" ";
    }
    getNext(s,next);
//    for(int i = 0; i<length; i++)
//    {
//        cout<<next[i]<<" ";
//    }
    cout<<Find(s, pat, next)<<endl;
    return 0;
}

还有改进的失败函数

posted @ 2014-08-16 09:45  Haeckel  阅读(142)  评论(0)    收藏  举报