您的位置:首页 > 其它

KMP算法(待优化)--2015年7月25日14:04:25V1.0版

2015-07-25 14:31 543 查看
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

void makenext(const string str,int next[])   //next数组
{
    next[0] = 0;
    int maxs; //最大前缀后缀相等数目
    for(int i = 1,maxs = 0;i < str.length(); i++)
    {
        while( maxs > 0 && str.at(maxs) != str.at(i))    //当前缀下一位不等于后缀下一位时
        {
            //当匹配失败时,找到一个前缀序列,再与后缀匹配
            //a[0]...a[maxs].... a[i-maxs]...a[i-1]  a[i]...
            //                      匹配      匹配    匹配失败
            //                      a[0]....a[max-1] a[max]...
            //                                匹配    判断是否匹配
            //                        a[0]...a[j-1]   a[j]
            maxs = next[maxs - 1];  //next[max - 1]相当于匹配失败后,前缀作为后缀,所对应的前缀
        }
        if(str.at(maxs) == str.at(i))   //如果maxs和i匹配,则最大前缀后缀数目+1
        {
            maxs++;
        }
        next[i] = maxs;
    }

//    测试输出
//    cout<< str << endl;
//    for(int i = 0; i < str.length(); i++)
//        cout << next[i] << " ";
//    cout << endl;
}

bool KMP(const string motherstr,const string patternstr,int next[])  //KMP算法
{
    int maxs;   //最大前缀后缀相等数目
    makenext(patternstr,next);
    for(int i = 0,maxs = 0; i < motherstr.length(); i++)
    {
        while(maxs > 0 && patternstr[maxs] != motherstr[i]) //当前缀下一位不等于后缀下一位时
        {
            //PS:这里的原理和makeNext方法里面一样,只不过这里的模式串是patterntr,母串是mothertr
            maxs = next[maxs - 1];
        }
        if(patternstr[maxs] == motherstr[i])    //如果maxs和i匹配,则最大前缀后缀数目+1
        {
            maxs++;
        }
        if(maxs == patternstr.length())    //当最大前缀后缀相等数目与patternstr一样长时,则证明匹配成功
        {
            //测试匹配成功时,返回patternstr在motherstr里的位置
            //cout<<i-maxs+1;
            return true;
        }
    }
    return false;
}
int main()
{
//测试KMP算法是否正确
    string str1= "aaaac";
    string str2= "aaaa";
    int next[100];
    if(KMP(str1,str2,next))
        cout<<"Yes."<<endl;
    else
        cout<<"NO."<<endl;
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: