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
题意描述:给出两个字符串,然后让这两个字符串合并输出。并且输出是最小字典序的形式。
#include<stdio.h>
#include<string.h>
int next[100100];
char a[100100],b[100100];
void get_next(char b[],int lb)
{
int i=1,j=0;
while(i<lb)
{
if(j==0&&b[i]!=b[j])
next[i++]=0;
else if(j>0&&b[i]!=b[j])
j=next[j-1];
else
{
next[i]=j+1;
i++;
j++;
}
}
}
int kmp(char a[],char b[],int la,int lb)
{
int i=0,j=0;
while(i<la)
{
if(j==0&&a[i]!=b[j])
i++;
else if(j>0&&a[i]!=b[j])
j=next[j-1];
else
{
i++;
j++;
}
if(i==la)
return j;
}
}
int main(void)
{
int la,lb,count,count1,sun;
int i,j;
while(~scanf("%s%s",a,b))
{
la=strlen(a);
lb=strlen(b);
sun=strcmp(a,b);
get_next(b,lb);
count=kmp(a,b,la,lb);
get_next(a,la);
count1=kmp(b,a,lb,la);
if(count>count1)
printf("%s%s\n",a,b+count);
else if(count1>count)
printf("%s%s\n",b,a+count1);
else if(count==count1)
{
if(sun<0)
printf("%s%s\n",a,b+count);
else if(sun>=0)
printf("%s%s\n",b,a+count);
}
}
return 0;
}

本文介绍了一种处理字符串合并的问题,当遇到两个字符串时,如何将它们合并成一个新的字符串,同时确保合并后的字符串在字典序中是最小的。通过使用KMP算法,文章提供了一个具体的实现方案。
1249

被折叠的 条评论
为什么被折叠?



