题目链接:https://vjudge.net/problem/HDU-2594
思路:连接连个字符串求next数组。注意next数组的值不能超过len1或者len2
#include<bits/stdc++.h>
using namespace std;
const int maxn=50005;
int nex[maxn*2];
int len1,len2;
void GetNext(string P)
{
int p_len = P.size();
int i = 0; // P 的下标
int j = -1;
nex[0] = -1;
while (i < p_len)
{
if (j == -1 || P[i] == P[j])
{
i++;
j++;
nex[i] = j;
}
else
j = nex[j];
}
if(nex[p_len]>min(len1,len2)) ///特判:最长的前后缀长度没有超过len1和len2;
{
for(int i=0; i<min(len1,len2); i++)
{
cout<<P[i];
}
printf(" %d\n",min(len1,len2));
}
else
{
int ans=nex[p_len];
if(ans) ///判断是否存在最长前后缀
{
for(int i=0; i<ans; i++)
{
cout<<P[i];
}
printf(" ");
}
printf("%d\n",ans);
}
}
int main()
{
string s1,s2,s3;
while(cin>>s1>>s2)
{
len1=s1.size();
len2=s2.size();
memset(nex,0,sizeof(nex));
s3=s1+s2; ///连接
GetNext(s3);
}
}