题目:
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
题目的意思是给你两个字符串,要你求出它们最长匹配的字符串的个数,且这个最长匹配的字符串是第一个字符串的前缀以及第二个字符串的后缀。
前缀:字符串中除最后一个字符外的其它从第一个字符开始的子串。
后缀:字符串中除第一个字符外的其它以最后一个字符结尾的子串。
其实这道题可以看作是求最长公共前缀后缀,因为一个是前缀,一个是后缀,因此可以将这两个字符串连接起来,利用kmp中的失配函数求出最长公共前缀后缀即可。
只是要注意这种情况:
abcabcabcabc
abcabcabcabcabc
12
abcabc
abc
3
处理方法:最终取两个字符串中的最小长度的字符串(事先需计算出谁的长度最小)。
另外,这道题的两个字符串中可能出现空格。
至于什么是kmp,可以百度大神的博客学习(其实我也不是特别懂)。
参考代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int N = 100000+10;
string s1, s2;
int nexts[N];
void init() {
s1.clear();
s2.clear();
fill(nexts, nexts+N, 0);
}
void cal_next(string s1, int *nexts) {
int len = s1.length();
int i, j;
nexts[0] = -1;
for (int i = 1;i < len;++i) {
j = nexts[i-1];
while (s1[j+1] != s1[i] && (j > -1)) {
j = nexts[j];
}
if (s1[i] == s1[j+1]) {
nexts[i] = j + 1;
}
else {
nexts[i] = -1;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
//cin.get();
while (getline(cin, s1)) {
//cin.get();
getline(cin, s2);
//cout << s1 << " " << s2 << endl;
int len1 = s1.length(), len2 = s2.length();
int minlen = min(len1, len2);
s1 = s1 + s2;
cal_next(s1, nexts);
if (nexts[s1.length()-1]+1 > minlen) {
for (int i = 0;i < minlen;++i) {
cout << s1[i];
}
cout << " ";
cout << minlen << endl;
}
else {
for (int i = 0;i < nexts[s1.length()-1]+1;++i) {
cout << s1[i];
}
if (nexts[s1.length()-1]+1 != 0) cout << " ";
cout << nexts[s1.length()-1]+1 << endl;
}
init();
}
return 0;
}