#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int maxn=1010;
int next[maxn],n,num;
void getnext(char s[] ,int len){
int j=-1;
next[0]=-1;
for(int i=1;i<len;i++){
while(j!=-1&&s[i]!=s[j+1]){
j=next[j];
}
if(s[i]==s[j+1])
j++;
next[i]=j;
}
}
bool kmp(char text[],char pattern[]){
int n=strlen(text),m=strlen(pattern);
getnext(pattern,m);
int j=-1;
for(int i=0;i<n;i++){ //因爲kmp算法不是像getnext一樣自我匹配,
while(j!=-1&&text[i]!=pattern[j+1]){//所以必須從頭(i=0)開始遍歷!
j=next[j];
}
if(text[i]==pattern[j+1]){
j++;
}
if(j==m-1){
return true;
}
}
return false;
}
int main(){
char s[maxn];
scanf("%s",s);
getnext(s,strlen(s));
for(int i=0;i<strlen(s);i++)
printf("%d ",next[i]);
return 0;
}
複習next函數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.