Sample Input
clinton
homer
riemann
marjorie
Sample Output
0
rie 3
输入两个字符串 ,求最长相同前后缀
直接把两个字符串连接在一起求next就行了,唯一要注意的就是长度不能大于原来任一字符串的长度,如果长度大于了,要选择len1和len2中较小的一个输出。
# include <cstdio>
# include <cstring>
using namespace std ; char s1[] ;
char s2[] ;
char s3[] ;
int next[] ;
int len1 , len2; void getNext()
{
int j, k;
j = ; k = -; next[] = -;
while(j < len1+len2)
if(k == - || s1[j] == s1[k])
next[++j] = ++k;
else
k = next[k];
} int main ()
{
while (scanf("%s%s" , &s1 , &s2) != EOF)
{
len1 = strlen(s1) ;
len2 = strlen(s2) ;
strcat(s1 , s2) ;
getNext() ;
int i ;
for (i = ; i < next[len1 + len2] ; i++)
{
s3[i] = s1[i] ;
}
s3[i] = '\0' ;
if (next[len1 + len2])
{
if (next[len1 + len2] > len1 ||next[len1 + len2] > len2)
{
if (len1 > len2)
printf("%s %d\n" ,s2 ,len2) ;
else
{
s3[len1] = '\0' ;
printf("%s %d\n" ,s3 ,len1) ;
}
}
else
printf("%s %d\n" ,s3 ,next[len1 + len2]) ;
}
else
printf("0\n") ;
} return ;
}