poj 2752 Seek the Name, Seek the Fame

来源:互联网 发布:l女装淘宝店名 编辑:程序博客网 时间:2024/06/01 16:02

求字符串的前缀和后缀相同的前-后缀长度

kmp算法的应用,求出的next数组即为最长的前缀和后缀相同的前-后缀长度,递归求next数组,直到不存在这样的前后缀,每次得到的数组即为一种满足题意的前后缀长度,数组不包含该字符串本身的长度,即最大的前后缀长度为数组长度。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;void getNext(char *str,int *next){int j = 0;int len = strlen(str);next[1] = 0;for(int i = 2;i<len+1;i++){while(j>0&&str[j]!=str[i-1]){j = next[j];}if(str[j]==str[i-1])j++;next[i] = j;}}char str[400005];int next[400005];void Output(int len){if(next[len]==0)return;Output(next[len]);printf("%d ",next[len]);}int main(){while(scanf("%s",str)!=EOF){getNext(str,next);int len = strlen(str);Output(len);printf("%d\n",len);}}


原创粉丝点击