HDU 2594 Simpsons’ Hidden Talents (KMP)

题意

求出最长的串长度,该串既是s1的前缀又是s2的后缀.

思路

把两个字符串连起来求一下前缀数组next[]即可~当然要用"#"或者其他非小写字母连接起来防止两个字符串真的混起来,比如s1="a",s2="aaaa"这种情况。

代码

  [cpp] #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <set> #include <stack> #include <queue> #define MID(x,y) ((x+y)/2) #define MEM(a,b) memset(a,b,sizeof(a)) #define REP(i, begin, end) for (int i = begin; i <= end; i ++) using namespace std; typedef long long LL; string s, s2; int next[100005], len; void get_next(){ len = s.size(); int j = -1; next[0] = -1; for (int i = 1; i < len; i ++){ while(j > -1 && s[i] != s[j+1]) j = next[j]; if (s[i] == s[j+1]) j ++; next[i] = j; } } int main(){ //freopen("test.in", "r", stdin); //freopen("test.out", "w", stdout); while(cin >> s){ cin >> s2; s = s + "#" + s2; //cout << s << endl; get_next(); if (next[len-1] >= 0){ for (int i = 0; i <= next[len-1]; i ++){ cout << s[i]; } cout << " "; } cout << next[len-1]+1 << endl; } return 0; } [/cpp]
原文地址:https://www.cnblogs.com/AbandonZHANG/p/4114116.html