ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-08-19 16:01:31  阅读:219  来源: 互联网

标签:again HDU 100010 s2 s1 sdfg 1867 include asdf


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

标签:again,HDU,100010,s2,s1,sdfg,1867,include,asdf
来源: https://blog.csdn.net/touso/article/details/99731691

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有