題目:
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
題目的意思是給你兩個字符串,要你求出它們最長匹配的字符串的個數(shù),且這個最長匹配的字符串是第一個字符串的前綴以及第二個字符串的后綴。
前綴:字符串中除最后一個字符外的其它從第一個字符開始的子串碍现。
后綴:字符串中除第一個字符外的其它以最后一個字符結(jié)尾的子串合武。
其實這道題可以看作是求最長公共前綴后綴讯私,因為一個是前綴,一個是后綴阵苇,因此可以將這兩個字符串連接起來备禀,利用kmp中的失配函數(shù)求出最長公共前綴后綴即可洲拇。
只是要注意這種情況:
abcabcabcabc
abcabcabcabcabc
12
abcabc
abc
3
處理方法:最終取兩個字符串中的最小長度的字符串(事先需計算出誰的長度最小)曲尸。
另外赋续,這道題的兩個字符串中可能出現(xiàn)空格。
至于什么是kmp另患,可以百度大神的博客學(xué)習(xí)(其實我也不是特別懂)蚕捉。
參考代碼:
#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;
}