poj 2752

http://poj.org/problem?id=2752

题意:给一个字符串,问你前缀和后缀相同的位置有哪些

思路:很意思的一个题目,也发现了next数组隐藏着一个规律,就是next[len]的值就是最大前缀后缀相同的个数

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <vector>
 4 #include <algorithm>
 5 const int maxn = 1e6+5;
 6 using namespace std;
 7 
 8 int next[maxn];
 9 char str[maxn];
10 
11 vector<int>s;
12 
13 void getnext(char str[])
14 {
15     int len = strlen(str);
16     next[0] = -1;
17     int i = 0,j = -1;
18     while(i<len)
19     {
20         if(j==-1||str[i]==str[j])
21             next[++i] = ++j;
22         else
23             j = next[j];
24     }
25 }
26 
27 
28 int main()
29 {
30     while(~scanf("%s",str))
31     {
32         s.clear();
33         memset(next,0,sizeof(next));
34         getnext(str);
35         int len = strlen(str);
36         while(len){
37             s.push_back(len);
38             len = next[len];
39         }
40         sort(s.begin(),s.end());
41         printf("%d",s[0]);
42         for(int i = 1;i<s.size();i++)
43             printf(" %d",s[i]);
44         printf("
");
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/Tree-dream/p/7429371.html