hdu 1867:A + B for you again(kmp)

8 篇文章 1 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=1867

Problem Description

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

题意分析:

两个字符串a,b,如果a的末尾和b的开头相同或者b的末尾和a的开头相同,相同部分只输出一次。输出可以去掉字符最多的那一个,如果相同输出字典序最小的。

解题思路:

假设a在前面,求相同的字符有多少,用b做子串, 匹配之后,如果匹配到了a的末尾,那么就是末尾与b有相同的,而此时b的匹配位置j就是相同长度。

b在前面时道理是一样的,分别求出两个重复部分比较输出。

#include <stdio.h>
#include <string.h>
#define N 100020
char str1[N], str2[N];
int next[N];
void get_next(char *b, int lenb)
{
	memset(next, 0, sizeof(next));
	int i=1, j=0;
	next[0]=-1;
	while(i<lenb)
	{
		if(j==-1 || b[i]==b[j])
		{
			i++;
			j++;
			next[i]=j;
		}
		else j=next[j];
	}
}
int kmp(char *a, char *b, int lena, int lenb)
{
	get_next(b, lenb);
	int i=0, j=0;
	while(i<lena && j<lenb)
	{
		if(j==-1 || a[i]==b[j])
		{
			i++;
			j++;
		}
		else j=next[j];
	}
	if(i==lena)
		return j;
	return 0;
}
int main()
{
	int lena, lenb, k1, k2;
	while(scanf("%s%s", str1, str2)!=EOF)
	{
		lena=strlen(str1);
		lenb=strlen(str2);
		k1=kmp(str1, str2, lena, lenb);
		k2=kmp(str2, str1, lenb, lena);
		if(k1>k2)
			printf("%s%s\n", str1, str2+k1);
		else if(k1<k2)
			printf("%s%s\n", str2, str1+k2);
		else{
			if(strcmp(str1, str2)<0)
				printf("%s%s\n", str1, str2+k1);
			else
				printf("%s%s\n", str2, str1+k1);
		}
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

张宜强

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

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

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

打赏作者

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

抵扣说明:

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

余额充值