题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2594
题意:给两个字符串,求第一串的前缀与第二串的后缀匹配的最长序列以及长度。
分析:一开始觉得把两个字符串连接起来,不就和next数组的含义是一样的吗,很开心的敲了,结果WA了。。。原来直接用next数组的话会把后缀延伸到第一串当中,或者把前缀延伸到第二串当中,这样就不符合题意了。所以要继续next下去,直到长度小等于短串的长度,就OK啦。
代码:
#include<cstdio>
#include<cstring>
const int N=50000+5;
char a[N*2],b[N];
int next[N*2];
void getnext()//求next数组的模板
{
next[0]=-1;
int i=1,j=0,len=strlen(a);
while(i<len)
{
if(j==-1||a[i]==a[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
int main ()
{
//freopen("in.txt","r",stdin);
while(~scanf("%s%s",a,b))
{
int lena=strlen(a),lenb=strlen(b);
strcat(a,b);
getnext();
int ans=next[strlen(a)];
while(ans>lenb||ans>lena) ans=next[ans];//直到长度小等于短串的长度
if(ans==0) printf("0\n");
else
{
a[ans]=0;//去掉后面的就是前缀啦
printf("%s %d\n",a,ans);
}
}
return 0;
}