HDU 2594 KMP
题意:给定两个字符串s1,s2,求最长的s1前缀s使得s为s2的最长后缀,输出该字符串和其长度。
题解:调换s1和s2的顺序,用KMP求解即可。
#include <bits/stdc++.h> using namespace std; const int N=50005; char s1[N],s2[N]; int len1,len2; int next_val[N]; void getnext_val() { int i=0,j=-1; next_val[i]=-1; while(i<len2){ if(j==-1||s2[i]==s2[j]){ i++;j++; if(s2[i]!=s2[j])next_val[i]=j; else next_val[i]=next_val[j]; } else j=next_val[j]; } } int kmp() { int i=0,j=0; while(i<len1){ if(j==-1||s1[i]==s2[j]){ i++; j++; } else j=next_val[j]; } return j; } int main() { while(scanf("%s%s",s2,s1)!=EOF){ len1=strlen(s1); len2=strlen(s2); getnext_val(); int k=kmp(); if(k==0) printf("0\n"); else{ for(int i=0;i<k;i++) printf("%c",s2[i]); printf(" %d\n",k); } } return 0; } /* clinton homer riemann marjorie */
附上几个传送门:
http://www.cnblogs.com/kuangbin/archive/2012/08/14/2638803.html
http://blog.csdn.net/xingyeyongheng/article/details/9285989
http://www.cnblogs.com/Su-Blog/archive/2012/09/13/2684049.html