Simpsons’ Hidden Talents
Homer: Marge, I just figured out a way to discover some of the talents we weren’t aware we had.
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have a talent in politics, OK?
Marge: OK.
Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have a talent in politics, OK?
Marge: OK.
Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.
The lengths of s1 and s2 will be at most 50000.
clinton
homer
riemann
marjorie
Sample Output
0
rie 3
题意:
给出两个字符串,寻找前一个字符串的假前缀和后一的字符串的假后缀,输出最长相等的部分及其长度。
解题思路:
水题一道,刚开始看的时间以为题目中的前后缀是真前后缀,结果是假前后缀。这里的真前后缀不包括字符串本身,而假前后缀包括字符串本身。这一题中就是假前后缀。思路是将两个字符串连接起来,运用next数组的信息,输出结果。
这一题可以加深对next数组的理解。
代码:
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,m,lena,lenb;
char a[100010];
char b[50010];
int next[100010];
while(scanf("%s%s",a,b)!=EOF)
{
lena=strlen(a);
lenb=strlen(b);
strcat(a,b);
i=1;j=0;
m=0;
memset(next,0,sizeof(next));
while(i<lena+lenb)
{
if(j==0&&a[i]!=a[j])
{next[i]=0;i++;}
else if(j>0&&a[i]!=a[j])
j=next[j-1];
else
{
next[i]=j+1;
i++;j++;
}
}//这里next数组中最后存入的数字就是所求最长的前后缀。
m=next[lena+lenb-1];
if(m>=lena)
m=lena;
if(m>=lenb)
m=lenb;//这两个判断是防止出现aaa aaaaa,和aaaaa aaa,这两种情况。
if(m>0)
{
a[m]='\0';
printf("%s",a);
printf(" ");
}
printf("%d\n",m);
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
}
return 0;
}