题意:找到两个字符串最长前缀后缀匹配。比并且是输出字符串较小的。
#include <iostream>
#include <cstdio>
#include<limits>
#include <map>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
const int MAXN=100005;
char s1[MAXN], s2[MAXN];
int next1[MAXN];
int next2[MAXN];
void getnext(char s[], int next[])
{
int i=0, j=-1;
next[0]=-1;
int len = strlen(s);
while(i<len)
{
if(j==-1||s[i]==s[j])
next[++i]=++j;
else
j=next[j];
}
return ;
}
int KMP(char s3[], char s4[], int next[])
{
int i=0, j=0;
int lena=strlen(s3), lenb=strlen(s4);
while(i<lena&&j<lenb)
{
if(s3[i]==s4[j]||j==-1)
i++, j++;
else
j=next[j];
}
if(i==lena)
return j;
return 0;
}
int main()
{
while(~scanf("%s %s", s1, s2))
{
getnext(s1, next2);
getnext(s2, next1);
int x=KMP(s1, s2, next1);
int y=KMP(s2, s1, next2);
if(x>y)
printf("%s%s\n", s1,s2+x);
else if(x==y)
{
if(strcmp(s1, s2)>0)
printf("%s%s\n", s2, s1+x);
else
printf("%s%s\n", s1, s2+x);
}
else
printf("%s%s\n", s2,s1+y);
}
return 0;
}