G - A + B for you again

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>

char s1[100010],s2[100010];
int next[100010];

void get_next(char s[])
{
	int i,j,len;
	
	memset(next,0,sizeof(next));
	i = 1;
	j = 0;
	len = strlen(s);
	
	while(i < len)
	{
		if(j == 0&&s[i] != s[j])
		{
			i ++;
		}
		if(j > 0&&s[i] != s[j])
		{
			j = next[j - 1];
		}
		if(s[i]==s[j])
		{
			next[i] = j + 1;
			i ++;
			j ++;
		}
	}
}
int kmp(char s1[],char s2[])
{
int i,j,lens1,lens2;
	
	i = 0;
	j = 0;
	lens1 = strlen(s1);
	lens2 = strlen(s2);
	get_next(s2);
	
	while(j < lens1)
	{
		if(i == 0&&s2[i] != s1[j])
		{
			j ++;
		}
		if(i > 0&&s2[i] != s1[j])
		{
			i = next[i-1];
		}
		if(s2[i] == s1[j])
		{
			i ++;
			j ++;
		}
	}
	return i;
}
int main()
{
	int t1,t2,len1,len2;
	
	while(~ scanf("%s",s1))
	{
		scanf("%s",s2);
		len1 = strlen(s1);
		len2 = strlen(s2);
		t1 = kmp(s1,s2);
		t2 = kmp(s2,s1);
		if(t1 == t2)
		{
			if(strcmp(s1,s2) < 0)
			{
				printf("%s%s\n",s1,s2+t1);
			}
			else
			printf("%s%s\n",s2,s1+t1);
		}
		else if(t1>t2)
		{
			printf("%s%s\n",s1,s2+t1);
		}
		else
		printf("%s%s\n",s2,s1+t2);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/y1356998843/article/details/81198967
今日推荐