HDU 2594 Simpsons’ Hidden Talents(字符串-KMP)

来源:互联网 发布:玉溪鑫科软件 编辑:程序博客网 时间:2024/06/01 09:44

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
clintonhomerriemannmarjorie
 

Sample Output
0rie 3
 

Source
HDU 2010-05 Programming Contest
 

Recommend
lcy

题目大意:

给两个字符串s1s2,求出最长的相同的s1的前缀和s2的后缀的长度。如s1的前缀和s2的后缀没有公共部分,输出0


解题思路:

此题可以很好地利用KMP算法中next数组的性质,next[i]表示的是模式串前i个字符组成的字符串中,

前缀和后缀最长的相同部分的长度。

所以本题只需将s1s2两个字符串拼接起来,整体作为模式串,求出其next数组即可,最后的答案就是next[长度之和]

但有一点需要注意,直接拼接会引入错误,如“aaa”和“a”这两个字符串,拼接后成为“aaaa”,这样求出的答案为3,这是不对的,明显超出了原先串的长度。所以可以在拼接时,中间加一个分割符,比如“|”等(除小写字母均可),这样可以不修改求next数组的算法,直接得出答案。当然也可以判断一下,取得出的答案与两串长度的较小值。


参考代码:

#include <iostream>#include <cstring>#include <string>using namespace std;const int MAXN = 100010;string s1, s2, str;int next[MAXN];void getNext(string pattern) {    memset(next, 0, sizeof(next));    for (int i = 1; i < pattern.length(); i++) {        int j = i;        while (j > 0) {            j = next[j];            if (pattern[j] == pattern[i]) {                next[i+1] = j + 1;                break;            }        }    }}void output() {    if (next[str.length()]) {        cout << str.substr(0, next[str.length()]) << " " << next[str.length()] << endl;    } else {        cout << 0 << endl;    }}int main() {    ios::sync_with_stdio(false);    while (cin >> s1) {        cin >> s2;        str = s1 + "|" + s2;        getNext(str);        output();    }    return 0;}

扩展阅读:
http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

0 0
原创粉丝点击