Simpsons’ Hidden Talents HDU - 2594

题目传送门

题意:给你两个字符串,求一个最长子串即是s1的前缀也是s2的后缀。

思路:一个裸的KMP,直接求就可以了。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXN 100010
#define MAXE 100
#define INF 1000000000
#define MOD 10001
#define LL long long
#define ULL unsigned long long
#define pi 3.14159

using namespace std;

int nex[MAXN];
int n, m;

void get_nex(const string &s) {
    memset(nex, 0, sizeof(nex));
    for (int i = 1, j = 0; i < s.length(); ++i) {
        while (j && s[i] != s[j]) {
            j = nex[j];
        }
        if (s[i] == s[j]) {
            j++;
        }
        nex[i + 1] = j;
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    string str1, str2;
    while (cin >> str1 >> str2) {
        n = (int) str1.length();
        m = (int) str2.length();
        str1 += str2;
        get_nex(str1);
        int len = min(min(n, m), nex[str1.length()]);
        for (int i = (int) str2.length() - len; i < str2.length(); ++i) {
            cout << str2[i];
        }
        if (len) {
            cout << " ";
        }
        cout << len << endl;
    }
    return 0;
}

你可能感兴趣的:(KMP)