KMP之C++实现

关于KMP的讲解请参考上篇《三步学通KMP》(https://blog.csdn.net/helloworldchina/article/details/104465772),这里笔者仅补充一下C++代码的实现,见下:
1 next[]数组代码:

int* KmpNext(string str)
{
    int* next = new int[str.size()];
    next[0] = 0;
    for(int j = 1,k = 0; j < str.size(); j++)
    {
        while(k > 0 && str[k] != str[j])
        {
            k = next[k - 1];
        }
        if(str[j] == str[k])
        {
            k++;
        }
        next[j] = k;
    }
    return next;
}

2 kmp代码

int KMP(string s, string t,int* next)
{//s主串  t 模式串
    for(int i = 0, j = 0; i < s.size(); i++)
    {

        while(j > 0 && s[i] != t[j])
        {
            j = next[j - 1];    //下一个匹配位为next数组的第j-1位
        }
        if(s[i] == t[j])
        {
            j++;//主串通过i进行加1,模式串通过j加1
        }
        if(j == t.size())
        {
            return i-j+1;//返回匹配位置
        }
    }
    return -1;
}

3 打印next[]数组代码

void PrintNext(string s)
{
    std::cout << "********************" << std::endl;
    int *nextI=NULL;
    nextI = KmpNext(s);
    std::cout << "模式串:'"+s+"'的next[]数组为:[";
    for(int i = 0; i < (s.size()); i++)
    {
        std::cout<<*(nextI+i)<<" ";

    }
    std::cout<<"]"<<std::endl;
    std::cout<<"模式串长度为:"+std::to_string(s.size())+" "<<std::endl;


}

4 主函数代码

int main() 
{
    //std::cout << "Hello, World!" << std::endl;
    string s = "CDFGFABABAFABABAAAQWEDC";
    string t = "ABABAA";
    int* next = KmpNext(t);
    int res = KMP(s, t,next);
    if (res!=-1)
    {
        std::cout<<"起始位置为:"+std::to_string(res)+" "<<std::endl;;
    }
    else std::cout<<"主串中不包含字符串:"+t<<std::endl;
    PrintNext("ABCDABD");
    PrintNext("ABABAA");
    PrintNext("ABAABCAC");


    return 0;

}

5运行结果
在这里插入图片描述

发布了17 篇原创文章 · 获赞 9 · 访问量 5853

猜你喜欢

转载自blog.csdn.net/helloworldchina/article/details/104570826