本题是加深对kmp中next数组的认识的好题,也可以说是体现next数组的精髓的一题。
题目大意:给定一个字符串,比如“alala”,找出所有的字串满足该字串即是他的前缀又是他的后缀,输出他们的长度:
其中,“alala”,满足该字符串的有a,ala,alala;即输出1 2 3即可。
alala中next数组中存储的对应值分别为0 0 1 2 3;字符串的长度为5,即abala肯定满足即是自己的前缀又是自己的后缀,所以5输出,next[5]中存的值是3,next[3]中存的值是1;
即输出1 3 5;
刚好符合了next函数的本质。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<string> 5 using namespace std; 6 char str[400005]; 7 int next[400005]; 8 int ans[400005]; 9 void get_next() 10 { 11 12 int i=0,j=-1; 13 next[0]=-1; 14 int len=strlen(str); 15 while(i<len) 16 { 17 18 if(j==-1||str[i]==str[j]) 19 { 20 i++;j++; 21 next[i]=j; 22 } 23 else 24 j=next[j]; 25 26 } 27 //for(i=0;i<=len;i++) 28 // printf("%d ",next[i]); 29 //printf("\n"); 30 } 31 int main() 32 { 33 while(cin>>str) 34 { 35 memset(next,0,sizeof(next)); 36 get_next(); 37 memset(ans,0,sizeof(ans)); 38 int k=1; 39 int len=strlen(str); 40 ans[0]=len; 41 int j=len; 42 while(next[j]>0)//注意next[len]中存的也是值的,即next[len-1]+1,这个地方纠结一上午 43 { 44 //cout<<next[j]<<endl; 45 ans[k++]=next[j];//这里的j刚开始理解为了第j个字母所对应的next值了,所以一直没想通 46 j=next[j]; 47 } 48 for(j=k-1;j>=0;j--) 49 { 50 printf("%d",ans[j]); 51 if(j+1) 52 printf(" "); 53 } 54 printf("\n"); 55 56 57 } 58 return 0; 59 60 61 }