题目:
Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
Output
Print the ultimate string by the book.
Sample Input
asdf sdfg asdf ghjk
Sample Output
asdfg asdfghjk
题意:
寻找两个字符串的前后缀最大相等部分(第一个字符串的前缀第二个字符串的后缀相等,或者第二个字符按串的前缀或者后缀,选取两者中最长输出),输出一个串不相等部分+相等部分+另一个串的不相等部分。当两个字符串完全不相等时间,按长短输出,长度短的在前,长度较长的在后。长度相等时,按字典序较小的在前,较大的在后输出。
思路:
分别计算字符串a+b和b+a的最长公共前后缀max1,max2;
如果max1>max2,则输出b,和a除了公共部分的字符;
如果max1<max2,则输出a,和b除了公共部分的字符;
如果max1=max2,比较形成字符串的字典序,输出字典序小的;
代码:
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
int nextt[210000],n;
void getnext(string s)
{
int i=0,j=-1;
nextt[0]=-1;
while(i<n)
{
if(j==-1||s[i]==s[j])
{
i++;j++;
nextt[i]=j;
}
else
j=nextt[j];
}
}
int main()
{
string a,b,s;
while(cin>>a>>b)
{
s=a+b;
n=s.length();
int l1=a.length();
int l2=b.length();
memset(nextt,0,sizeof(nextt));
getnext(s);
/*for(int i=0;i<=n;i++)
printf("%d\n",nextt[i]);*/
int max1=0,max2=0;
int minn=min(l1,l2);
max1=nextt[n];
if(max1>minn)//注意 aaaaa a 这类情况
max1=minn;
memset(nextt,0,sizeof(nextt));
getnext(b+a);
max2=nextt[n];
if(max2>minn)//注意 aaaaa a 这类情况
max2=minn;
if(max1>max2)
{
cout<<b;
int l=a.length();
for(int i=max1;i<l;i++)
printf("%c",a[i]);
cout<<endl;
}
else if(max1<max2)
{
cout<<a;
int l=b.length();
for(int i=max2;i<l;i++)
printf("%c",b[i]);
cout<<endl;
}
else
{
string x,y;
x=a;
for(int i=max1;i<l2;i++)
x=x+b[i];
y=b;
for(int i=max1;i<l1;i++)
y=y+a[i];
if(x<y)
cout<<x<<endl;
else
cout<<y<<endl;
}
}
return 0;
}