题目描述:
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.
输入:
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 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.
样例输入:
clinton
homer
riemann
marjorie
样例输出:
0
rie 3
code:
题目大意:找前一个字符串的前缀和后一个字符串的后缀一样的最长长度
KMP 的基础题目
思路:由于是求b的后缀最长是a的前缀。不妨将a,b连接起来,求next数组,这样next[len](len表示a,b连接后的长度)则可以表示匹配到的最大长度。 不过需要注意的是next[len]不能大于a,b的长度。
#include<stdio.h>
#include<string.h>
const int maxn=1e6+50;
char a[maxn];
char b[maxn];
int nexxt[maxn];
int m,n;
void init()
{
int maxx;
int i=0,j=-1;
int nn=strlen(a);
nexxt[0]=-1;
while(i<nn)
{
if(j==-1||a[i]==a[j])
{
i++;
j++;
nexxt[i]=j;
}
else j=nexxt[j];
}
maxx=nexxt[nn];
while(maxx>m||maxx>n)
maxx=nexxt[maxx];//注意最大的可能比他们本身长
for(int i=0;i<maxx;i++)
{
printf("%c",a[i]);
}
if(maxx>0)printf(" ");
printf("%d\n",maxx);
}
int main()
{
while(~scanf("%s%s",a,b))
{
n=strlen(b);
int j=strlen(a);
m=j;
for(int i=0;i<n;i++)
{
a[j++]=b[i];
}
a[j]='\0';
init();
}
return 0;
}