Seek the Name, Seek the Fame(KMP算法之next数组的深入理解实例)
2016-01-28 13:17
399 查看
[align=center]Seek the Name, Seek the Fame[/align]
DescriptionThe little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escapefrom such boring job, the innovative little cat works out an easy but fantastic algorithm:Step1. Connect the father's name and the mother's name, to a new string S.Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).Example: Father='ala', Mother='la', we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix stringsof S? (He might thank you by giving your baby a name:)InputThe input contains a number of test cases. Each test case occupies a single line that contains the string S described above.Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.OutputFor each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.Sample Input
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 15436 | Accepted: 7808 |
ababcababababcabab aaaaaSample Output
2 4 9 18 1 2 3 4 5
大致题意:给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。大致思路:如左图,假设黑色线来代表字符串str,其长度是len,红色线的长度代表next[len],根据next数组定义易得前缀的next[len]长度的子串和后缀next[len]长度的子串完全相同(也就是两条线所对应的位置)。我们再求出next[len]位置处的next值,也就是图中蓝线对应的长度。同样可以得到两个蓝线对应的子串肯定完全相同,又由于第二段蓝线属于左侧红线的后缀,所以又能得到它肯定也是整个字符串的后缀。所以对于这道题,求出len处的next值,并递归的向下求出所有的next值,得到的就是答案。#include<stdio.h>#include<string.h>int next[400005];char str[400005];int sum[400000];void getNext(char *str,int next[]){int k=strlen(str);next[0]=-1;int i=0,j=-1;while (i<k){if (j==-1||str[i]==str[j]){i++;j++;next[i]=j;}elsej=next[j];}}int main(){while (scanf("%s",str)!=EOF){int k=0,i;int len=strlen(str);getNext(str,next);for(i=len;i!=0;){sum[k++]=next[i];i=next[i];}for(i=k-2;i>=0;--i)printf("%d ",sum[i]);printf("%d\n",len);}return 0;}
相关文章推荐
- 位运算 的探究
- 6.2 Controllers -- Representing Multipe Models
- sln里边的内容
- DrawMenus.cs
- LCA小结
- sl4j in project
- Use the endorsed directory mechanism to place jaxb-api.jar(jaxb-api.jar、jaxws-api.jar与jdk1.6不兼容问题)
- ElasticSearch 2 (3) - Breaking Changes
- TextEntity.cs
- 运用平行四边形法则解题二例
- java 并发笔记
- ios 取出subviews中指定subview
- Leetcode Regular Expression Matching
- Java中的集合
- 前端工程师使用node.js打造日记社区教程之二
- [s3c2416x移植u-boot-2015.10]如何在u-boot工程中取消对NorFlash的支持
- git查看某一个檔案的詳細commit record
- OracleDatabase.cs
- android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
- 抽样 拉希里法的变形(Lahiri)