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

题意:给定两个字符串,把一个字符串接在另一个字符串的后面,相接部位若有相同,则可以略去其中一个字符串的相同部分,输出拼接后最小长度的字符串,若有两种最小长度的字符串,输出字典序较小的那个。

分析:可以用kmp匹配一个字符串的尾部和另一个字符串的首部相同的最大长度,然后交换两个字符串的次序,再来一次匹配,根据匹配出来的长度来决定把那个字符串放在前面。

#include<stdio.h>
#include<string.h>
char s1[100010],s2[100010];
int next[100010];
void get_next(char s[],int len)
{
	int i = 1,j = 0;
	while(i < len)
	{
		if(j == 0 && s[i] != s[j])
		{
			next[i] = 0;
			i ++;
		}
		else if(j > 0 && s[i] != s[j])
			j = next[j-1];
		else
		{
			next[i] = j + 1;
			i ++; j ++;
		}
	}
}
int kmp(char p[],char q[])
{
	int i = 0, j = 0,lenp,lenq;
	lenp = strlen(p);lenq = strlen(q);
	get_next(q,lenq);
	while(i < lenp) //&& j < lenq)
	{
		if(j == 0 && p[i] != q[j])
			i ++;
		else if(j > 0 && p[i] != q[j])
			j = next[j-1];
		else
		{
			i ++; j ++;
		}
	}
	//if(i == lenp)//来排除主串包含在子串中间的某个部分(而不是主串的后缀 ) 
		return j;
	//return 0;
}
int main()
{
	int l1,l2;
	while(scanf("%s%s",s1,s2) != EOF)
	{
		l1 = kmp(s1,s2);
		l2 = kmp(s2,s1);
		if(l1 > l2)
			printf("%s%s",s1,s2+l1);
		else if(l1 < l2)
			printf("%s%s",s2,s1+l2);
        else
        {
            if(strcmp(s1, s2) < 0)
            	printf("%s%s",s1,s2+l1);
            else
            	printf("%s%s",s2,s1+l2);
        }
        printf("\n");
	}	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值