Topic Links:
http://acm.hdu.edu.cn/showproblem.php?pid=2594
Main topic:
Give you two strings of S1 and S2, which is the longest string and length of both the S1 prefix and the S2 suffix.
Ideas:
KMP algorithm next[j] = = k is the essence of the current letter mismatch, the pattern string of the first K (s0~sk-1) and position J before
K-item (SJ-1-K~SJ-1) is equal, this K-value is all that satisfies the above situation maximum. So the meaning of Next[len]
is the longest prefix of the pattern string and the length of the string equal to the suffix.
Using the nature of next[], the string S2 is connected to the S1 behind. Next[] Array for S1. Well, now the Next[len]
is the longest length of the S1 prefix and S2 suffix, which is only full when the length of the <= string S1 and the length of the S2
of the foot. If the above conditions are not met, the found string is not a substring of S1 or S2. Let Len = Next[len] continue to check
Find the longest length that satisfies the condition. Find the string that satisfies the maximum length of the request, output S0~s (len-1).
AC Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace Std;char s1[100010],s2[50010];int next[100010],len,len1,len2;void GetNext (char *s) { int i = 0,j =-1; Next[0] =-1; while (i <= len) { if (j = =-1 | | s[i] = = S[j]) { i++,j++; Next[i] = j; } else j = next[j]; }} int main () { while (cin >> s1 >> S2) { len1 = strlen (S1); Len2 = strlen (s2); strcat (S1,S2); Len = len1 + len2; GetNext (S1); while (Next[len] > Len1 | | Next[len] > Len2) len = Next[len]; len = Next[len]; for (int i = 0; i < len; ++i) cout << s1[i]; if (len) cout << '; cout << len << endl; } return 0;}
HDU2594 Simpsons ' Hidden talents "KMP"