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
0 rie 3
#include<stdio.h>
#include<string.h>
char p[50010],s[50010];
int next[50010];
int cnt;
void get_next()
{
next[0]=-1;
int j=0,k=-1;
int len=strlen(p);
while(j<len)
{
if(k==-1 || p[j] == p[k])
{
j++;
k++;
next[j]=k;
}
else
k=next[k];
}
}
int Kmp()
{
int i=0,k=0;
get_next();
int len=strlen(s);
while(i<len)
{
if(k==-1 || s[i]==p[k])
{
i++;
k++;
cnt=k;
}
else
k=next[k];
}
}
int main()
{
while(~scanf("%s%s",p,s))
{
cnt=0;
Kmp();
if(cnt==0)
printf("0\n");
else
{
for(int i=0;i<cnt;i++)
printf("%c",p[i]);
printf(" %d\n",cnt);
}
}
return 0;
}