题目链接:hdu 2954 Simpsons’ Hidden Talents
题目大意:给出两个字符串,找出一个子串,为s1的前缀,s2的后缀, 要求子串最长,并且输出该子串。
解题思路:将s1和s2首尾相连,然后求出next数组的next[n+m]的位置,然后和n、m取最小值即为答案。
#include <stdio.h> #include <string.h> #define min(a,b) (a)<(b)?(a):(b) const int N = 1e5+5; int n, m, next[N]; char s1[N], s2[N]; void getNext () { int p = 0; m = strlen(s1+1); for (int i = 2; i <= m; i++) { while (p > 0 && s1[p+1] != s1[i]) p = next[p]; if (s1[p+1] == s1[i]) p++; next[i] = p; } } int main () { while (scanf("%s%s", s1+1, s2+1) == 2) { n = min (strlen(s1+1), strlen(s2+1)); strcat (s1+1, s2+1); getNext (); int ans = min (next[m], n); for (int i = 1; i <= ans; i++) printf("%c", s1[i]); if (ans) printf(" "); printf("%d\n", ans); } return 0; }
hdu 2954 Simpsons’ Hidden Talents(KMP),布布扣,bubuko.com
hdu 2954 Simpsons’ Hidden Talents(KMP)
原文:http://blog.csdn.net/keshuai19940722/article/details/21483799