hdu 1867 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

题意:给定两个串,连接两个串的公共前后缀输出,如果没有公共前后缀,按照字典序小的串在前连接输出,不存在包含关系(例如abcd bc 输出abcdbc)

思路:当匹配到了主串的末尾时,直接返回此时模式串的下标,表示最后匹配位置,也就是公共前后缀部分。我们需要尽可能取较多的公共匹配部分,所以,取较大下标。

数据:

输入

abcd   bcd

aaa b

abcd bc

输出

abcd

aaab

abcd bc


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 100010;
#define inf 0x3f3f3f3f
char str1[maxn],str2[maxn];
int next1[maxn],next2[maxn];
int l1,l2;
void get_next(int *next,char s[])
{
	int i,j;
	next[0] = j = -1;
	i = 0;
	while(s[i]!='\0')
	{
		while(j!=-1&&s[i]!=s[j])
			j = next[j];
		next[++i] = ++j;
	}
	return;
}

int KMP(char *s1,char *s2,int length,int *next)
{
	int i,j;
	i = j = 0;
	while(s1[i]!='\0')
	{
		while(j!=-1&&s1[i]!=s2[j])
			j = next[j];
		i++;
		j++;
		if(s1[i]=='\0')
			return j;
			
	}
	return 0;
}

int main()
{
	int dis1,dis2;
//	freopen("in.txt","r",stdin);
	while(scanf("%s%s",str1,str2)!=EOF)
	{
		memset(next1,0,sizeof(next1));
		memset(next2,0,sizeof(next2));
		l1 = strlen(str1);
		l2 = strlen(str2);
		get_next(next1,str1);
		get_next(next2,str2);
		dis1 = KMP(str1,str2,l2,next2);
		dis2 = KMP(str2,str1,l1,next1);
		if(dis1 > dis2||(dis1==dis2&&strcmp(str1,str2)<0))
		{
			printf("%s%s\n",str1,str2+dis1);
		}
		else if(dis1 < dis2||(dis1==dis2&&strcmp(str1,str2)>=0))
			printf("%s%s\n",str2,str1+dis2);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值