思路:利用KMP算法求出第二个字符串最后一个字符的后缀长度即可。
#include <iostream>
using namespace std;
#define N 50010
char parent[N];
char child[N];
int Next[N];
void getNext(char child[])
{
int n = strlen(child);
int i = 0, j = -1;
Next[0] = -1;
while(i < n)
{
if (-1 == j || child[i] == child[j])
{
++i;
++j;
Next[i] = j;
}
else
{
j = Next[j];
}
}
}
int KMP(char parent[], char child[])
{
memset(Next, 0, sizeof(Next));
getNext(child);
int i = -1, j = -1;
int pn = strlen(parent), cn = strlen(child);
int maxN = 0;
while(i < pn)
{
if (-1 == j || parent[i] == child[j])
{
++i;
++j;
}
else
{
j = Next[j];
}
if (i == pn)
{
maxN = j;
}
}
if (maxN == 0)
{
printf("0\n");
return maxN;
}
for (i = 0;i < maxN; ++i)
{
printf("%c", child[i]);
}
printf(" %d\n", maxN);
return maxN;
}
int main()
{
while(scanf("%s %s", child, parent) != EOF)
{
KMP(parent, child);
}
return 0;
}