标签:
题目链接:http://poj.org/problem?id=2752
| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 17393 | Accepted: 8907 | 
Description
Input
Output
Sample Input
ababcababababcabab aaaaa
Sample Output
2 4 9 18 1 2 3 4 5
题目大意:给定一个字符串输出其中既是前缀又是后缀的子串的长度
解题思路:借助KMP算法中的next数组 next[i]的值表明在字符串中i之前的子串长度为next[i]的前缀和后缀相同
| 下标 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
 | 
| 字符串 | a | b | a | b | c | a | b | a | b | a | b | a | b | c | a | b | a | b | 
 | 
| Next[i] | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 4 | 3 | 4 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 
 | 
AC代码:
 
1 #include <stdio.h> 2 #include <string.h> 3 int next[400010]; 4 char str[400010]; 5 void getnext() //先求出next数组 6 { 7 int i = 0,j = -1; 8 next[0] = -1; 9 int len = strlen(str); 10 while (i < len) 11 { 12 if (j == -1 || str[i]==str[j]) 13 { 14 ++ i; 15 ++ j; 16 next[i] = j; 17 } 18 else 19 j = next[j]; 20 } 21 } 22 int main() 23 { 24 int num[400010],i,k; 25 while (scanf("%s",str)!=EOF) 26 { 27 int len = strlen(str); 28 getnext(); 29 num[0] = len; 30 k = 1; 31 while (next[num[k-1]]) //借助next数组将既是前缀有是后缀的子串的长度 32 { 33 num[k] = next[num[k-1]]; 34 k ++; 35 } 36 for (i = k-1; i > 0; i --) 37 printf("%d ",num[i]); 38 printf("%d\n",num[0]); 39 } 40 return 0; 41 }
POJ 2752 Seek the Name, Seek the Fame
标签:
原文地址:http://www.cnblogs.com/yoke/p/5858834.html