一道kmp的题。
题意好理解,给你两个字符串a ,b,在输出要求下输出a+b或者b+a。先说一下这个‘+“法的规定。若a的某一最大后缀和b的某一最大前缀相等,则可合并。例:abcdef+defppp=abcdefppp。
输出要求,a+b和b+a中长度较短的字符串。若两个字符串长度相等,则输出字典序较小的。
做法:kmp分别求:a+b时a的后缀和b的前缀的最大相同序列。
b+a时b的后缀和a的前缀的最大相同序列。
然后输出选相同序列的较大者输出。
若相等,则再比较a和b的字典序,再输出。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#define INF 0x3f3f3f3f
#define maxn 100000+10
using namespace std;
char str1[maxn], str2[maxn];
int nex[maxn];
void get_nex(char *x, int m, int *nex)
{
int i, j;
j = nex[0] = -1;
i = 0;
while (i < m)
{
while (j != -1 && x[i] != x[j])
j = nex[j];
nex[++i] = ++j;
}
}
int kmp(char *str1, char *str2)
{
int i = 0, j = 0;
int len1 = strlen(str1), len2 = strlen(str2);
get_nex(str2, len2, nex);
while (i < len1&&j < len2)
{
if (j == -1 || str1[i] == str2[j])
{
i++;
j++;
}
else j = nex[j];
}
if (i == len1) return j;
return 0;
}
int main()
{
while (scanf("%s %s", str1, str2) != EOF)
{
int temp1 = kmp(str1, str2);
int temp2 = kmp(str2, str1);
if (temp1 > temp2)
{
printf("%s", str1);
printf("%s\n", &str2[temp1]);
}
else if (temp1 < temp2)
{
printf("%s", str2);
printf("%s\n", &str1[temp2]);
}
else
{
if (strcmp(str1, str2) < 0) printf("%s%s\n", str1, &str2[temp1]);
else printf("%s%s\n", str2, &str1[temp2]);
}
}
return 0;
}