原文:
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
题意描述:
找出第一个子串的前缀和第二个子串后缀相同的部分,如果有就输出没有的话就输出0;
解题思路:
用next数组存储第一个子串的前缀和后缀的信息,然后比较两个子串如果相等就往后继续找记录j的数值 ,如果不相等就让第一个子串从头开始找第二个子串中与他相同的子串
解题技巧:
如果在找的时候要是不相等就让第二个子串的当前位置不变,让第一个子串回到当前next数组中next[j]的值的位置,因为要找的 是第二个子串的后缀在后面要么会出现与第一个子串前缀相同的后缀,要么就不会出现;
AC代码:
#include<stdio.h>
#include<string.h>
char s[100005],p[50005];
int next[100005];
int n,m;
void Get_next()
{
int i=1,j=0;
next[0]=-1;
while(i<n)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
void kmp()
{
int i=0,j=0;
while(i<m)
{
if(j==-1||s[j]==p[i])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==0)
printf("0\n");
else
{
for(i=0; i<j; i++)
printf("%c", s[i]);
printf(" %d", j);
printf("\n");
}
}
int main()
{
while(scanf("%s %s", s,p)!=EOF)
{
n=strlen(s);
m=strlen(p);
Get_next();
kmp();
}
return 0;
}
中文题目:
荷马:玛吉,我刚刚想出了一个方法来发现一些我们不知道自己有什么才能。
玛吉:是的,是什么?
荷马:以我为例。我想知道我是否有政治天赋,好吗?
玛吉:好的。
荷马:所以我取了一些政治家的名字,比如克林顿,然后试着找出最长前缀的长度。
在克林顿的名字里,那是我名字的后缀。这就是我和克林顿这样的政治家的关系
玛吉:为什么选择最长的前缀作为后缀?是吗?
荷马:嗯,我们的才能深深地隐藏在我们自己的内心,玛吉。
玛吉:那你离这儿有多远?
荷马:0!
玛吉:我一点也不惊讶。
荷马:但你知道,你内心深处一定隐藏着一些真正的数学天赋。
玛吉:怎么了?
荷马:里曼和马乔里给了3个!!!
玛吉:谁是黎曼?
荷马:没关系。
编写一个程序,当给定字符串s1和s2时,该程序将查找s1的最长前缀,即s2的后缀。
输入
输入由两行组成。第一行包含s1,第二行包含s2。您可以假设所有字母都是小写的。
输出
输出由一行组成,该行包含前缀为s1的最长字符串和后缀为s2,后跟该前缀的长度。如果最长的这样的字符串是空字符串,那么输出应该是0。
S1和S2的长度最多为50000。
Sample Input
clinton
homer
riemann
marjorie
Sample Output
0
rie 3
本文介绍了一种用于寻找两个字符串间最长前缀与后缀匹配部分的算法,并提供了详细的解题思路和AC代码示例。
238

被折叠的 条评论
为什么被折叠?



