HDU 2594 Simpsons’ Hidden Talents KMP
传送门http://acm.hdu.edu.cn/showproblem.php?pid=2594
题目要求的是求第一个字符串的前缀是第二个字符串的后缀。当然要求最长
我还以为是第一个字符串在第二个字符串出现,不用后缀。。。。。。
WA了一次。。
看题要仔细。。。。
根据KMP
字符查找过程中,会有一个状态值j,这个j表示s2已经匹配了s1多少个字符。所以当全部匹配完之后,j即为以s2的最后一个字符结尾,和s1前缀匹配的最长字符串。也就是答案。
#include<cstdio> #include<cstring> const int MAXN = 50000+10; int p[MAXN]; void getFail(const char *s,const int &n) { p[0]=p[1]=0; for(int i=1;i<n;i++) { int j = p[i]; while(j && s[i]!=s[j]) j=p[j]; if(s[i]==s[j]) j++; p[i+1] = j; } } int kmp(const char *s1,const char *s2,const int &n,const int &m) { int j = 0; for(int i=0;i<m;i++) { while(j && s1[j] != s2[i]) j = p[j]; if(s1[j] == s2[i]) j++; } return j; } int main() { char s1[MAXN],s2[MAXN]; while(~scanf("%s",s1)) { scanf("%s",s2); int n=strlen(s1); int m=strlen(s2); getFail(s1,n); int ans = kmp(s1,s2,n,m); if(ans) printf("%s ",s2 + m - ans); printf("%d\n",ans); } }
新 blog : www.hrwhisper.me