【字符串入门专题1】B - Simpsons’ Hidden Talents hdu2594【kmp】

时间:2021-09-13 22:14:39

Simpsons’ Hidden Talents



Problem Description 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 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 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.
 
Sample Input
clinton
homer
riemann
marjorie
 
Sample Output
0
rie 3


题意:输出字符串1的前缀和字符串2的后缀最大公共字符串。

思路:用kmp模板里定义next数组方法1是无法写这道题的,我用的是第二种很轻松

就解决辣

我是next数组定义方法2的链接哦~~ 

(本来心里只钟情于把定义1作为自己主模板的,然额,当自己发现方法二不仅 可以处理字符匹配,还可以求前缀后缀最长的公共部分,感觉好厉害的样子,           还明显比方法1的代码简短好多啊,心里的天平已经悄悄歪了,哎哎哎,            自己好善变啊)

       这道题自己画蛇添足的地方是,判断两个字符串的长度大小,加了这个条件反倒         wrong了,喂喂喂,人家没有说字符串1的长度必须比字符串2小哇。



#include<cstdio>
#include<cstring>
#define N 55000

char s1[N],s2[N];
int NEXT[N];
void get_NEXT()//建立next数组 (用的kmp模板里next数组定义2的方法)
{
int j,k;
NEXT[0] = k = -1;
j = 0;
while(s2[j]!='\0')
{
if(k==-1||s2[k] == s2[j])
NEXT[++j] = ++k;
else
while(k!=-1)
k = NEXT[k];
}
return;
}
int kmp()//字符串匹配函数
{
int i,j;
i = j = 0;
while(s1[i]!='\0')
{
if(j != -1&&s2[j]=='\0')
j = NEXT[j];
else
{
while(j!=-1&&s2[j]!=s1[i])
j = NEXT[j];
j++;
i++;
}
}
return j;
}
int main()
{
int ans;
while(scanf("%s",s2)!=EOF)
{
scanf("%s",s1);
get_NEXT();
ans = kmp();
s2[ans] = '\0';
if(!strlen(s2))
printf("0\n");
else
printf("%s %d\n",s2,ans);
}
return 0;
}