Simpsons’ Hidden Talents
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9823 Accepted Submission(s): 3393
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
题意概括:
判断s1的前缀和s2的后缀的最长相同长度。
解题分析:
水题,有两种方法:
1、将s2接到s1的后边用一个next数组来记录相同前后缀的长度,最后输出next数组最后一位记录的数值就可以了需要注意的是判断s1为aaaaaaa, s2为aa的这种特殊数据。
2、这种是我用的方法,不用判断上述的特殊情况。因为需要判断s1的前缀与s2的后缀的最长相同长度,所以将s1最为模式串建一个next数组,再去跟s2匹配,也就是用KMP来写。这种方法需要注意的是在用KMP时一定要把文本串,也就是s2跑完才能结束,最后返回j的值就是相对应的最长相同长度。
AC代码:
#include<stdio.h>
#include<string.h>
#define N 50010
char s1[N], s2[N];
int next[N], len1, len2;
void get_next()
{
int i = 1, j = 0, k;
while(i < len1){
if(j == 0 && s1[i] != s1[j]){
next[i] = 0;
i++;
}
else if(j > 0 && s1[i] != s1[j])
j = next[j-1];
else{
next[i] = j+1;
i++;
j++;
}
}
}
int KMP(void)
{
int i = 0, j = 0;
while(i < len2){//不需要再加j < len1,因为需要把s2跑完不然返回的j值就不是最长的相同长度,而是s1中与s2最长的匹配长度
if(j == 0 && s1[j] != s2[i])
i++;
else if(j > 0 && s1[j] != s2[i])
j = next[j-1];
else{
i++;
j++;
}
}
return j;
}
int main()
{
int i, j, Max, p;
while(~scanf("%s%s", s1, s2)){
len1 = strlen(s1);
len2 = strlen(s2);
get_next();
p = KMP();
for(int i=0; i<p; i++)
printf("%c",s1[i]);
if(p)
printf(" ");
printf("%d\n",p);
}
return 0;
}