A + B for you again(最长公共前缀和后缀)HDU - 1867

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>
#include<iostream>
using namespace std;
int nxt[100010];
char s1[100010],s2[100010];
void getnext(char *str,int m)//对s2进行预处理
{
	m=strlen(str);
	int k=0,i=1;
	nxt[0]=0;
	while(i<m)
	{
		if(str[i]==str[k])
		nxt[i++]=++k;
		else
		{
			if(k==0)
			nxt[i++]=0;
			else
			k=nxt[k-1];
		}
	}
}
int kmp(char *str1,char *str2,int n,int m)//求最长公共前缀和后缀
{
	n=strlen(str1);
	m=strlen(str2);
	getnext(str2,m);
	int i=0,j=0;
	while(i<n&&j<m)
	{
		if(str1[i]==str2[j])
		{
			i++;
			j++;
		}
		else
		{
			if(j==0)
			i++;
			else
			j=nxt[j-1];
		}
	}
	if(j==m&&i==n-1||i==n)//s2字符串找完了,或找到s1数组的结尾了
	return j;
	return 0;
}
int main()
{
	while(~scanf("%s%s",s1,s2))
	{
		int len1=strlen(s1),len2=strlen(s2),k1,k2;
		k1=kmp(s1,s2,len1,len2);//求s1前缀和s2后缀相同的部分
		k2=kmp(s2,s1,len2,len1);//求s2前缀和s1后缀相同的部分
		if(k1>k2)
		printf("%s%s\n",s1,s2+k1);
		else if(k2>k1)
		printf("%s%s\n",s2,s1+k2);
		else//若相同,按字典序较小的顺序输出
		{
			if(strcmp(s1,s2)<0)
			printf("%s%s\n",s1,s2+k1);
			else
			printf("%s%s\n",s2,s1+k2);
		}
	}
	return 0;
}
上一篇:用户与计算机的几个简单交互游戏(猜数字、猜单词、剪刀石头布)


下一篇:Review and start again——First Period JAVA web Program hotelmanagement:9.A bug