A + B for you again(最长公共前缀和后缀)HDU - 1867

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>
#include<iostream>
using namespace std;
int nxt[100010];
char s1[100010],s2[100010];
void getnext(char *str,int m)//对s2进行预处理
{
	m=strlen(str);
	int k=0,i=1;
	nxt[0]=0;
	while(i<m)
	{
		if(str[i]==str[k])
		nxt[i++]=++k;
		else
		{
			if(k==0)
			nxt[i++]=0;
			else
			k=nxt[k-1];
		}
	}
}
int kmp(char *str1,char *str2,int n,int m)//求最长公共前缀和后缀
{
	n=strlen(str1);
	m=strlen(str2);
	getnext(str2,m);
	int i=0,j=0;
	while(i<n&&j<m)
	{
		if(str1[i]==str2[j])
		{
			i++;
			j++;
		}
		else
		{
			if(j==0)
			i++;
			else
			j=nxt[j-1];
		}
	}
	if(j==m&&i==n-1||i==n)//s2字符串找完了,或找到s1数组的结尾了
	return j;
	return 0;
}
int main()
{
	while(~scanf("%s%s",s1,s2))
	{
		int len1=strlen(s1),len2=strlen(s2),k1,k2;
		k1=kmp(s1,s2,len1,len2);//求s1前缀和s2后缀相同的部分
		k2=kmp(s2,s1,len2,len1);//求s2前缀和s1后缀相同的部分
		if(k1>k2)
		printf("%s%s\n",s1,s2+k1);
		else if(k2>k1)
		printf("%s%s\n",s2,s1+k2);
		else//若相同,按字典序较小的顺序输出
		{
			if(strcmp(s1,s2)<0)
			printf("%s%s\n",s1,s2+k1);
			else
			printf("%s%s\n",s2,s1+k2);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值