题目描述
按照改进KMP算法计算指定模式串的nextval向量。
输入格式
一组由字母和数字组成的模式串,每个模式串输入一行,长度不小于1,不大于200。
输出格式
输入每个模式串的nextval向量,每个nextval向量输出一行,各数值之间用一个空格隔开。
输入样例
aabb
abcabc
输出样例
-1 -1 1 0
-1 0 0 -1 0 0
代码展示
#include<bits/stdc++.h>
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
#define max 201
void getNextVal(char t[],int *next){
int len=strlen(t);
next[0]=-1;
if(len==1) return ;
int k=next[0];
int j=0;
while(j<len){
if(k==-1||t[j]==t[k]){
j++;
k++;
if(t[j]==t[k]){
next[j]=next[k];
}
else{
next[j]=k;
}
}
else k=next[k];
}
}
int main(){
char t[max];
while(cin>>t)
{
int len=strlen(t);
int next[len+1];
getNextVal(t,next);
for(int i=0;i<len;i++){
cout<<next[i]<<" ";
}
cout<<endl;
}
return 0;
}