码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2203 亲和串 (KMP或者strstr)

时间:2015-02-13 14:51:48      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:hdu   kmp   


亲和串

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 8756    Accepted Submission(s): 3976

Problem Description
人随着岁数的增长是越大越聪明还是越大越笨,这是一个值得全世界科学家思考的问题,同样的问题Eddy也一直在思考,因为他在很小的时候就知道亲和串如何判断了,但是发现,现在长大了却不知道怎么去判断亲和串了,于是他只好又再一次来请教聪明且乐于助人的你来解决这个问题。
亲和串的定义是这样的:给定两个字符串s1和s2,如果能通过s1循环移位,使s2包含在s1中,那么我们就说s2 是s1的亲和串。
 

Input
本题有多组测试数据,每组数据的第一行包含输入字符串s1,第二行包含输入字符串s2,s1与s2的长度均小于100000。
 

Output
如果s2是s1的亲和串,则输出"yes",反之,输出"no"。每组测试的输出占一行。
 

Sample Input
AABCD CDAA ASD ASDF
 

Sample Output
yes no
 
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2203


题目分析:两种做法,自己敲一边kmp,或者直接调用strstr,首先l1 < l2直接输出no,否则将s1复制一次接在后面当作母串,s2当作模式串


KMP:

#include <cstdio>
#include <cstring>
int const MAX = 1e5 + 5;
int next[MAX], l1, l2, ll1;
char ss1[MAX], s2[MAX];
char s1[2 * MAX];

void get_next()
{
	int i = 0, j = -1;
	next[0] = -1;
	while(s2[i] != '\0')
	{
		if(j == -1 || s2[i] == s2[j])
		{
			i++;
			j++;
			if(s2[i] == s2[j])
				next[i] = next[j];
			else
				next[i] = j;
		}
		else
			j = next[j];
	}
}

bool KMP()
{
	get_next();
	int i = 0, j = 0;
	while(s1[i] != '\0')
	{
		if(j == -1 || s1[i] == s2[j])
		{
			i++;
			j++;
		}
		else
			j = next[j];
		if(j == l2 - 1)
			return true;
	}
	return false;
}

int main()
{
	while(scanf("%s %s", ss1, s2) != EOF)
	{
		ll1 = strlen(ss1);
		l1 = strlen(s1);
		l2 = strlen(s2);
		if(ll1 < l2)
		{
			printf("no\n");
			continue;
		}
		strcpy(s1, ss1);
		strcat(s1, ss1);
		if(KMP())
			printf("yes\n");
		else
			printf("no\n");
	}
}

strstr:

#include <cstdio>
#include <cstring>
int const MAX = 1e5 + 5;
int l1, l2, ll1;
char ss1[MAX], s2[MAX];
char s1[2 * MAX];

int main()
{
	while(scanf("%s %s", ss1, s2) != EOF)
	{
		ll1 = strlen(ss1);
		l1 = strlen(s1);
		l2 = strlen(s2);
		if(ll1 < l2)
		{
			printf("no\n");
			continue;
		}
		strcpy(s1, ss1);
		strcat(s1, ss1);
		if(strstr(s1, s2))
			printf("yes\n");
		else
			printf("no\n");
	}
}


 

HDU 2203 亲和串 (KMP或者strstr)

标签:hdu   kmp   

原文地址:http://blog.csdn.net/tc_to_top/article/details/43793609

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!