KMP算法代码

来源:互联网 发布:linux 光纤网卡 编辑:程序博客网 时间:2024/06/10 01:40

KMP算法

朴素的模式匹配
pat为参加比较的模式串
k为目标串起始位置

int Astring::Find(AString& pat, int k){    int i, j;    for(i = k; i <= curLength - pat.curLength; i++){        for(j = 0; j < pat.curLength; j++)            if(ch[i + j] != pat.ch[j])                break;        if(j == pat.curLength) return i;    }        return -1;//未找到字串位置}

朴素的模式匹配带有回溯, 一旦不等,将回溯,使i++,再进行下一次匹配,运行时间O(n*m)

KMP算法

使用了一个next函数避免回溯,当匹配遇到问题时,将移动字串的首个字符的位置到next[j]

计算next[j]的函数

void AString::getNext(int next[]){        int j = 0, k = -1, lenP = curLength;        next[0] = -1;        while(j < lenP)                if(k == -1 || ch[j] == ch[k]){                     j++;k++;                    next[j] = k;                 }        else k = next[k];}

KMP算法

int AString::fastFind(AString& pat, int k, int next[]) const{    //使用模式串pat从k开始寻找在当前串(*this)中匹配的位置    //若找到,则返回this串中开始字符的下标,否则返回-1    int posP = 0, posT = k;    int lengthP = pat.curLength;    int lengthT = curLength;    while(posP < lengthP && posT < lengthT)        if(posP == -1 || pat.ch[posP] == ch[posP]){            posP++;posT++;        }        else posP = next[posP];    if(posP < lengthP)         return -1;    else        return posT - lengthP;}
原创粉丝点击