KMP模式匹配-模板

KMP模式匹配-模板

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
//模板中的字符串都是用T[0]存储长度

//优化后的next计算数组
void get_nextval(char* T,int* nextval){
    int i=1,j=0;
    nextval[1]=0;
    while(i<T[0]){
        if(j==0 || T[i]==T[j]){
            ++i;++j;
            if(T[i]!=T[j]){
                nextval[i] = j;
            }else{
                nextval[i] = nextval[j];
            }
        }else{
            j = nextval[j];
        }
    }
}

//未优化的next计算数组
void get_next(char* T,int* next){
    int i=1,j=0;
    next[1]=0;
    while(i<T[0]){
        if(j==0 || T[i]==T[j]){
            ++i;++j;
            next[i]=j;
        }else{
            j = next[j];
        }
    }
}

//用T串从S串的pos位置开始进行匹配
int Index_KMP(char* S,char* T,int pos){
    int i = pos;
    int j = 1;
    int* next = new int[strlen(T) + 1];
    //get_next(T,next);//非优化版本
    get_nextval(T,next);//优化版本
    while(i<=S[0] && j<=T[0]){
        if(j==0 || S[i]==T[j]){
            ++i;++j;
        }else{
            j = next[j];
        }
    }
    delete[] next;
    if(j>T[0])return i-T[0];
    return 0;//匹配失败
}

//默认从S串的开头进行匹配的KMP函数
int KMP(char* S,char* T){
    return Index_KMP(S,T,1);
}

int main(){
    char aim[] = "&sasdffds";
    char bim[] = "&asdf";
    aim[0] = strlen(aim) - 1;
    bim[0] = strlen(bim) - 1;
    cout<< KMP(aim,bim) <<endl;
    return 0;
}


优化后直接使用

//优化后的next计算数组
void get_next(char* T,int* next){
    int i=1,j=0;
    next[1]=0;
    while(i<T[0]){
        if(j==0 || T[i]==T[j]){
            i++;j++;
            next[i] = (T[i]==T[j])? next[j] : j;
        }else{
            j = next[j];
        }
    }
}

//用T串从S串的pos位置开始进行匹配
int KMP(char* S,char* T,int pos){
    int i = pos;
    int j = 1;
    int* next = new int[strlen(T) + 1];
    get_next(T,next);//优化版本
    while(i<=S[0] && j<=T[0]){
        if(j==0 || S[i]==T[j]){
            i++;j++;
        }else{
            j = next[j];
        }
    }
    delete[] next;
    if(j>T[0])return i-T[0];
    return 0;//匹配失败
}

OK

posted @ 2020-09-30 22:07  SavenNeer  阅读(78)  评论(0编辑  收藏  举报