求两个串中的第一个最长子串(神州数码以前试题)。
如"abractyeyt","dgdsaeactyey"的最大子串为"actyet"。
先要找出 两个字符串的 所有的子字符串,然后求出所有子字符串的各自长度,找出最大的长度。
void main()
{
char *str1="asabcdefghbf2bcf";
char *str2="ebcevabcdefgg";
int len1 = strlen(str1);
int len2 = strlen(str2);
int i,j,m,n,k,tmp,start;
int count[100],count_1[100],count_2[100];
k = 0;
j = 0;
for(i = 0; i<len1 ;i++)
{
for(j = 0;j<len2 ;j++)
{
if( (str1[i] == str2[j]) )
{
m = i;
n = j;
while((str1[m] == str2[n]) && (str1[m] != '\0') &&(str2[n] != '\0'))
{
m++;
n++;
}
count[k] = m-i;
count_1[k] = m;
count_2[k] = i;
k++;
}
}
}
//一共有k个子序列 对他们进行排序,得到最大的
for(i = 0 ;i<k-1; i++)
{
if(count[i] >count[i+1])
{
tmp = count[i];
count[i] = count[i+1];
count[i+1] = tmp;
}
}
//最大的序列的长度为count[k-1],要输出这个序列,还要知道这个字符串的起始位置,使用count_1[] count_2[]
for(i = 0;i<k;i++)
{
if( (count_1[i]-count_2[i]) == count[k-1] )
{
start = count_2[i];
}
}
cout<<"start"<<start<<endl;
cout<<"length"<<count[k-1]<<endl;
cout<<"count_1: "<<count_1[start]<<endl;
cout<<"count_2: "<<count_2[start]<<endl;
//输出最大的子字符串,同时输出其长度
for(i = start ;i<(start+count[k-1]) ; i++)
{
printf("%c",str1[i]);
}
}