本篇博文来源于在阅读作者Liu Zhian所转载的文章《KMP算法讲解(next数组求解)》后根据自己理解所做的记录。
原文章写得非常详细的,配上相关图文说明,学习效果不错,在此感谢博主。有需要的同学移步到原文章,链接如下:
https://blog.csdn.net/qq_37174526/article/details/90141833
下面根据自己的理解写出了next数组求解的代码,两段代码程序实际上是一样的,只是我自己个人为了做个记录所以都贴上了:
#include <iostream>
#include <string>
using namespace std;
//通过计算返回子串的next数组
void get_next(const string &s, int *next)
{
next[0]=-1;
next[1]=0;
int k=0;
//相当于我们在已知next[j]的情况下求next[j+1]
for(int j=1; j<(s.size()-1); )
{
if(s[k]==s[j] || k==-1)
{
next[j+1]=k+1;
++k;
++j;
}
else
{
//while(t[k]!=t[j] && k!=-1) //此条件多余
k=next[k];
}
}
}
int main()
{
//string s1="goodgoogle";
string s2="google";
const int sz=s2.size();
int next[sz];
get_next(s2, next);
for(auto a: next)
cout<<a<<" ";
cout<<endl;
}
#include <iostream>
#include <string>
using namespace std;
//通过计算返回子串的next数组
void get_next(const string &s, int *next)
{
int j,k;
j=0;
k=-1;
next[0]=-1;
while(j<(s.size()-1))
{
if(k==-1 || s[j]==s[k])
{
++j;
++k;
next[j]=k;
}
else
k=next[k];
}
}
int main()
{
//string s1="goodgoogle";
string s2="google";
const int sz=s2.size();
int next[sz];
get_next(s2, next);
for(auto a: next)
cout<<a<<" ";
cout<<endl;
}
在此欢迎并感谢各位同学的批评与指正。