Input
Input consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.
Output
Output consists of a single line that contains the longest string that is a prefix of s1 and a suffix of s2, followed by the length of that prefix. If the longest such string is the empty string, then the output should be 0.
The lengths of s1 and s2 will be at most 50000.
Sample Input
clinton
homer
riemann
marjorie
Sample Output
0
rie 3
题意:求两串字符连接起来后前缀后缀公共元素的最长长度。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int N = 1000002;
int nextt[N];
char S[N], T[N];
int slen, tlen,len;
int sum;
void getnextt()
{
int j,k;
j=0;
k=-1;
nextt[0]=-1;
while(j < len)
if(k == -1 || T[j] == T[k])
{
j++;k++;
nextt[j]=k;
}
else
{
k=nextt[k];
}
}
int main()
{
int TT;
int i, cc,n;
while(~scanf("%s%s",T,S))
{
slen = strlen(S);
tlen = strlen(T);
for(int i=tlen;i<tlen+slen;i++)
T[i]=S[i-tlen];
len=tlen+slen;
getnextt();
while(nextt[len]>tlen||nextt[len]>slen)//这里很重要,一开始没写wa了好多发。如果得到的答案超过字符串a,b本身那就要缩小len的范围。令L1=next[len],得到的前L1项组成的字符串,其后缀一定与原字符串的后缀是相同的,所以L2=next[next[len]],L2也一定是原字符串的前缀后缀公共元素长度
len=nextt[len];
if(nextt[len])
{
for(int i=0;i<nextt[len];i++)
printf("%c",T[i]);
printf(" ");
}
printf("%d\n",nextt[len]);
}
return 0;
}

本文介绍了一种用于求解两字符串连接后前缀与后缀公共部分的最长长度的算法实现。该算法通过构建辅助数组nextt[]来高效地完成字符串匹配过程,并通过样例输入输出展示了算法的具体应用。
815

被折叠的 条评论
为什么被折叠?



