http://acm.hdu.edu.cn/showproblem.php?pid=2594
给定两个字符串,找到第一个字符串的前缀是第二个字符串的后缀且最长。我们可以把第二个字符串连接到第一个后面,利用KMP求next数组的原理快速得到答案。
AC代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int next[100010];
char T[100010],t[50010];
void getnext(){
int i=0, j=-1, n = strlen(T);
next[0] = -1;
while(i<n){
if(j == -1 || T[i] == T[j]){
i++,j++;
next[i] = j;
}
else j = next[j];
}
}
int main(){
while(scanf("%s%s",T,t) == 2){
int l1 = strlen(T), l2 = strlen(t);
strcat(T, t);
getnext();
int len = strlen(T), L = next[len];
while(L > l1) L--;//T=next[T];
while(L > l2) L--;//T=next[T];
if(!L) printf("%d\n",0);
else{
for(int i=len-L; i<len; i++)
printf("%c",T[i]);
printf(" ");
printf("%d\n",L);
}
}
//system("pause");
return 0;
}