练习54-求N个字符串的最长公共子串

/**************************************************************************
 54. 求N个字符串的最长公共子串,N<=20,字符串长度不超过255。
    例如:N=3,由键盘依次输入三个字符串为
      What is local bus ?
      Name some local buses.
      local bus is a high speed I/O bus close to the processer.
 则最长公共子串为"local bus"。
 *************************************************************************/

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

#define N 3
char *strs[N] = {"What is local bus ?",
			"Name some local buses.",
			"local bus is a high speed I/O bus close to the processer."
};

bool IsSubStr(char *s,int len,char *t)
{
	char *p,*q;
	int len_t;
	int i;

	for(len_t=strlen(t); len <= len_t; ++t,--len_t)
	{
		for(p=s,q=t,i=0; i<len; p++,q++,i++)
		{
			if(*p != *q)
				break;
		}
		if(i == len)
			return true;
	}

	return false;
}

void main()
{
	int i,j,k;
	int len;
	int maxlen = 0;
	bool flag = false;
	char maxsubstr[255];

	len=strlen(strs[0]);
	for(maxlen=len; maxlen>0; maxlen--)
	{
		for(i=0; i<=len-maxlen; i++)
		{
			for(j=1; j<N; j++)
			{
				if(!IsSubStr(strs[0]+i,maxlen,strs[j]))
					break;
			}
			if(j==N)
			{
				flag = true;
				break;
			}
		}
		if(flag)
			break;
	}

	for(k=0; k<maxlen; k++)
		maxsubstr[k] = *(strs[0]+i+k);
	maxsubstr[k] = '\0';
	
	printf("最长公共子串为\"%s\",长度为%d\n",maxsubstr,maxlen);
}


 

阅读更多
换一批

没有更多推荐了,返回首页