1. 程式人生 > >next數組模板 兩種寫法

next數組模板 兩種寫法

while ++ cstring int == out iostream ace return

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 int next[61]={0};
 6 //計算串str的next數組
 7 void getnext(char *str){
 8     int len=strlen(str);
 9     next[0]=next[1]=0;
10     for(int i=1;i<len;i++){
11         int j=next[i];
12         while
(j&&str[i]!=str[j]) j=next[j];//一直回溯j直到str[i]==str[j]或j減小到0 13 next[i+1]=str[i]==str[j]?j+1:0;//更新next[i+1] 14 } 15 } 16 int main(){ 17 char c[100]; cin>>c; 18 getnext(c); 19 for(int i=1;i<=strlen(c);i++){ 20 cout<<next[i]; 21 } 22 return
0; 23 }

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 int next[61]={0};
 6 //計算串str的next數組
 7 void getnext(char *str){
 8     int len=strlen(str);
 9     int j=0,k=-1;
10     next[0]=-1;
11     while(j<len){
12         if
(k==-1||str[j]==str[k]) next[++j]=++k; 13 else k=next[k]; 14 } 15 } 16 int main(){ 17 char c[100]; cin>>c; 18 getnext(c); 19 for(int i=1;i<=strlen(c);i++){ 20 cout<<next[i]; 21 } 22 return 0; 23 }

next數組模板 兩種寫法