A + B for you again (kmp算法的简单应用)

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

题意描述:用所给出的两个字符串,如果有一个字符串的前缀和另一个字符串的后缀相同,将只保留其中一个,将重合部分放到中间,组成行的字符串;例如:acbd  bdgh 新字符串:acbdgh,bdgh  acbd  新的字符串:acbdgh,如果两个字符串做前缀和做后缀时重合长度相同,就比较两个字符串的大小,小的放前面;

解题思路:其实只要理解题意题还是不难的,就是算出两个字符串分别做前后缀是的重合长度再比较着输出就行了,只要会kmp算法的简单应用就不算难;

Ac代码:

#include<stdio.h>
#include<string.h>
int next[200010];
int find(char s[],char ss[])
{
	int n,m;
	n=strlen(s);
    m=strlen(ss);
	int i=0,j=-1;
	next[0]=-1;
	while(i<m)
	{
		if(j==-1 || ss[i]==ss[j])
			next[++i]=++j;
		else
		    j=next[j];
	}
	i=0;j=0;
    int max=0;
    while(i<n)
    {
        if(j==-1 || s[i]==ss[j])
        {
        	i++;j++;
		}
		else
		j=next[j];
	}
	return j;
 } 
int main() 
{
	int i,j,k,x,y;
	char s[200200],ss[200010];
	while(~scanf("%s%ss",s,ss))
	{
		x=find(s,ss);
		y=find(ss,s);
		if(x>y)
		printf("%s%s\n",s,ss+x);
		else if(x<y)
		printf("%s%s\n",ss,s+y);
		else
		{
			if(strcmp(s,ss)<0)
        	printf("%s%s\n",s,ss+x);
        	else
        	printf("%s%s\n",ss,s+x);
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BayMin0520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值