题目:
clinton homer riemann marjorieSample Output
0 rie 3
题意:给你两个字符串,求出第一个字符串的一个前缀,且这个前缀是第二个字符串的后缀,如果不存在,输出-1;
思路:可以再建立个字符串,把这两个字符串合并,中间用一个!来连接,防止相连前缀的情况,然后nextt[len]就是这个拼起来的字符串的相等的前后缀了,len就是这个拼的字符串的长度,
// // Created by HJYL on 2019/8/16. // #include <iostream> #include <vector> #include <map> #include <string> #include <queue> #include <stack> #include <set> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; typedef long long ll; const int maxn=1e6+10; char str[maxn],str1[maxn],str2[maxn]; int nextt[maxn]; void getnext() { int i=0,j=-1; nextt[0]=-1; int len=strlen(str2); while(i<len) { if(j==-1||str2[i]==str2[j]) { i++,j++; // if(str2[i]!=str2[j]) nextt[i]=j; // else // nextt[i]=nextt[j]; } else j=nextt[j]; } } int main() { // freopen("C:\\Users\\asus567767\\CLionProjects\\untitled\\text","r",stdin); while(~scanf("%s%s",str,str1)) { int len=strlen(str); int len1=strlen(str1); int pos=0; for(int i=0;i<len;i++) str2[pos++]=str[i]; str2[pos++]=‘!‘; for(int i=0;i<len1;i++) str2[pos++]=str1[i]; getnext(); // cout<<len2<<"=len2"<<endl; // cout<<nextt[len2]<<"hhh"<<endl; // cout<<"str2="<<str2<<endl; if(nextt[pos]<=0) printf("0\n"); else { for (int i = 0; i < nextt[pos]; i++) printf("%c", str2[i]); printf(" %d\n", nextt[pos]); } } return 0; }
[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher J - Simpsons’ Hidden Talents HDU - 2594(kmp前后缀)
原文:https://www.cnblogs.com/Vampire6/p/11365307.html