代码改变世界

KMP算法

2023-11-27 10:25  宋海宾  阅读(8)  评论(0编辑  收藏  举报
#include <iostream>

using namespace std;


int *getNext(string pattern){
    int len = pattern.length();
    int *mnext= (int *)malloc(sizeof(int)* len);

    if( mnext == NULL ){
        return NULL;
    }

    mnext[0] = -1;

    int j = -1;
    for( int i = 1; i < len; i++ ){

        while(j != -1 && pattern[ j + 1 ] != pattern[i]){
            j = mnext[j];
        }

        if(pattern[j + 1] == pattern[i]){
            j++;
        }

        mnext[i]= j;
    }

    return mnext;

}

int kmpsearch(string texts, string pattern){
    int j;

    int *mnext = getNext(pattern);
    if(mnext == NULL){
        return -1;
    }

    j = 0;
    for (int i = 0; i < texts.length(); i++){

        while( j > 0 && pattern[j] != texts[i]){
            j = mnext[j -1] + 1;
        }

        if(pattern[j] == texts[i]){
            j++;
        }

        if(j == pattern.length() - 1){
            return i - j + 1;
        }
    }

    return -1;

}
int main(){
    int i;
    i = kmpsearch("abababc", "baba");

    cout<<i<<endl;
    return 0;
}