首页 > 技术文章 > KMP练习——KMP模式匹配 一(串)

zhchoutai 2017-07-27 12:25 原文

Description

求子串的next值,用next数组存放,所有输出

Input

输入一个字符串

Output

输出全部next值

Sample Input

abaabcac

Sample Output

0 1 1 2 2 3 1 2

 

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
void getNext(char *p,int *next)
{
    int j=0,k=-1;
    next[0]=-1;
    while(j<strlen(p)-1)
    {
        if(k==-1||p[j]==p[k])
        {
            j++;
            k++;
            next[j]=k;
        }
        else
            k=next[k];
    }
}
int main()
{
	char a[100];
	int i,next[100];
	while(gets(a))
    {
        getNext(a,next);
        cout<<next[0]+1;
        for(i=1;a[i]!=0;++i)
            cout<<" "<<next[i]+1;
        cout<<endl;
    }
	return 0;
}


KMP算法中怎样求NEXT函数,详细原理大家看看就好。。。

 

 

推荐阅读