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

题意描述:用所给出的两个字符串,如果有一个字符串的前缀和另一个字符串的后缀相同,将只保留其中一个,将重合部分放到中间,组成行的字符串;例如:acbd  bdgh 新字符串:acbdgh,bdgh  acbd  新的字符串:acbdgh,如果两个字符串做前缀和做后缀时重合长度相同,就比较两个字符串的大小,小的放前面;

解题思路:其实只要理解题意题还是不难的,就是算出两个字符串分别做前后缀是的重合长度再比较着输出就行了,只要会kmp算法的简单应用就不算难;

Ac代码:

#include<stdio.h>
#include<string.h>
int next[200010];
int find(char s[],char ss[])
{
	int n,m;
	n=strlen(s);
    m=strlen(ss);
	int i=0,j=-1;
	next[0]=-1;
	while(i<m)
	{
		if(j==-1 || ss[i]==ss[j])
			next[++i]=++j;
		else
		    j=next[j];
	}
	i=0;j=0;
    int max=0;
    while(i<n)
    {
        if(j==-1 || s[i]==ss[j])
        {
        	i++;j++;
		}
		else
		j=next[j];
	}
	return j;
 } 
int main() 
{
	int i,j,k,x,y;
	char s[200200],ss[200010];
	while(~scanf("%s%ss",s,ss))
	{
		x=find(s,ss);
		y=find(ss,s);
		if(x>y)
		printf("%s%s\n",s,ss+x);
		else if(x<y)
		printf("%s%s\n",ss,s+y);
		else
		{
			if(strcmp(s,ss)<0)
        	printf("%s%s\n",s,ss+x);
        	else
        	printf("%s%s\n",ss,s+x);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44584292/article/details/99841120