poj 3450 Corporate Identity (字符串_KMP)

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


题目大意:给定m个串,求每个串中都出现的最长子串,如果两个子串长度一样要求输出字典序小的一个答案。如果没有则输出“IDENTITY LOST”


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


测试数据:

2

abc

xyz

3

abc

axy

amg

3

abcabc

abcabcabc

acbacbabc


代码:

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


int next[210];
char str[4100][210];
char ans[210],tp[210];


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

	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;


	while (scanf("%d",&m),m) {

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


		ans[0] = '\0';
		stlen = strlen(str[0]);	//枚举第一个串中长度大于3的子串
		for (len = 1; 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("IDENTITY LOST\n");
		else printf("%s\n",ans);
	}
}

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

你可能感兴趣的:(poj 3450 Corporate Identity (字符串_KMP))