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;
}

猜你喜欢

转载自blog.csdn.net/queen00000/article/details/81168320