poj 3080 Blue Jeans (字符串__KMP)

题目链接:http://poj.org/problem?id=3080

题目大意:给定m个串,求长度大等于3且在每个串中都出现的最长子串,如果两个子串长度一样要求输出字典序小的一个答案。如果没有则输出“no significant commonalities".

解题思路:第枚举第一串的所有大等于3的子串,再与其他每个串进行匹配,如果能匹配到则更新答案。

测试数据:

5
2
ACTACTACTACT
ACTACTACTACT
3
ABCABC
ABCA
ABCAA
2
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
3
CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT

代码:

#include <stdio.h>
#include <string.h>


int Kmp(char *s1,char *s2) {

	int next[100];
	int i,j,k,len1,len2;
	len1 = strlen(s1);
	len2 = strlen(s2);


	i = 0,j = -1;
	next[0] = -1;
	while (i < len2) {

		if (j == -1 || s2[i] == s2[j])
			i++,j++,next[i] = j;
		else j = next[j];
	}


	i = j = 0;
	while (i < len1) {

		if (j == -1 || s1[i] == s2[j])
			i++,j++;
		else j = next[j];
		if (j == len2) return 1;
	}


	return 0;
}


int main()
{
	int i,j,k,t,m,flag,stlen,len;
	char str[11][100],ans[100],tp[100];


	scanf("%d",&t);
	while (t--) {

		scanf("%d",&m);
		for (i = 0; i < m; ++i)
			scanf("%s",str[i]);


		ans[0] = '\0';
		stlen = strlen(str[0]);	//枚举第一个串中长度大于3的子串
		for (len = 3; len <= stlen; ++len)	
			for (i = 0; i <= stlen - len; ++i) {
			
				for (k = 0,j = i; j < i + len; ++j)
					tp[k++] = str[0][j];
				tp[k] = '\0';
				for (k = 1; k < m; ++k)
					if (Kmp(str[k],tp) == 0) break;
				
					
				if (k == m) {
				
					if (strlen(ans) == len && strcmp(ans,tp) > 0)
						strcpy(ans,tp);
					if (strlen(ans) < len) strcpy(ans,tp);
				}
			}


		if (ans[0] == '\0') 
			printf("no significant commonalities\n");
		else printf("%s\n",ans);
	}
}

本文章为ZeroClock原创,但可以转载,因为我们是兄弟。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值