KMP

Problem Description

Generally speaking, there are a lotof problems about strings processing. Now you encounter another such problem.If you get two strings, such as “asdf” and “sdfg”, the result of the additionbetween them is “asdfg”, for “sdf” is the tail substring of “asdf” and the headsubstring of the “sdfg” . However, the result comes as “asdfghjk”, when youhave to add “asdf” and “ghjk” and guarantee the shortest string first, then theminimum 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 theirswon’t exceed 10^5 and won’t be empty.

Output

Print the ultimate string by thebook.

Sample Input

asdf sdfg
asdf ghjk

Sample Output

asdfg
asdfghjk
 

 

给出两个字符串,要求将其组合起来,首先保证组合后的长度最短,然后按照字典序最小的方式组合,并且保证组合后两个字符串中重复的部分去掉

KMP,组合有两种方式一个在前一个在前,为了满足规则,首先求出两种不同组合方式后前缀和后缀的长度,比较哪个字符串放在前面,若长度相同则用strcmp函数比较字典序决定哪个字符串放在前面



#include<stdio.h>
#include<string.h>
char a[200110],b[200010],c[100010],d[100010];
int next[200010],next1[200010],lena,lenb;
int get_next()
{
	int i=1,j=0;
	next[0]=0;
	while(i<lena)
	{
		if(j==0 && a[i]!=a[j])
		{
			next[i]=0;
			i++;
		}
		else if(j>0 && a[i]!=a[j])
			j=next[j-1];
		else
		{
			next[i]=j+1;
			i++;
			j++;
		}
	}
	return next[lena-1];
}
int get_next1()
{
	int i=1,j=0;
	next1[0]=0;
	while(i<lenb)
	{
		if(j==0 && b[i]!=b[j])
		{
			next1[i]=0;
			i++;
		}
		else if(j>0 && b[i]!=b[j])
			j=next1[j-1];
		else
		{
			next1[i]=j+1;
			i++;
			j++;
		}
	}
	return next1[lenb-1];
}
int main()
{
	int s,s1,i,lenc,lend;
	while(scanf("%s",a)!=EOF)
	{
		scanf("%s",b);
		strcpy(c,a);
		strcpy(d,b);
		strcat(a,b);
		strcat(b,c);
		lena=strlen(a);
		lenb=strlen(b);
		lenc=strlen(c);
		lend=strlen(d);
		s=get_next();
		s1=get_next1();
		//printf("%d %d\n",s,s1);
		if(s>s1)
		{
			for(i=0;i<lend-next[lena-1];i++)
				printf("%c",d[i]);
			printf("%s\n",c);	
		}
		else if(s<s1)
		{
			for(i=0;i<lenc-next1[lenb-1];i++)
				printf("%c",c[i]);
			printf("%s\n",d);	
		}
		else
		{
			if(strcmp(c,d)<0)
			{
				for(i=0;i<lenc-next[lena-1];i++)
					printf("%c",c[i]);
				printf("%s\n",d);		
			}
			else
			{
				for(i=0;i<lend-next1[lenb-1];i++)
					printf("%c",d[i]);
				printf("%s\n",c);	
			}
		}
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(next,0,sizeof(next));
		memset(next1,0,sizeof(next1));
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值