kmp next数组求法

时间:2021-04-12 11:45:51   收藏:0   阅读:0

以字符串aabaaf为例

next数组可能有几种表达方式

如 0 1 0 1 2 0

 -1 0 1 0 1 2

 -1 0 -1 0 1 -1

实际上他们的本质上都是一样的

第一种当前后缀不匹配时,j跳到next[j-1];

第二种j跳到next[j];

#include<iostream>
#include<cstring>
using namespace std;
void Getnext(string s,int * next)
{
    int j=0;
    next[0]=0;
    for(int i=1;i<s.size();i++)
    {
        while(j>0&&s[i]!=s[j])
        {
            j=next[j-1];
        }
        if(s[i]==s[j]) j++;
        next[i]=j;
    }
}
void display(int *next)
{
    for(int i=0;i<6;i++)
    {
        cout<<next[i]<<endl;
    }
}
int main()
{
    string a="aabaaf";
    int next[6];
    Getnext(a,next);
    display(next);
    return 0;
} 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!