题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <stdio.h>
int main()
{
char str1[300] = {0};
char str2[300] = {0};
char out[300] = {0};
gets(str1);
gets(str2);
/* 固定str1为最短的字符串 */
if(strlen(str1) > strlen(str2))
{
char temp[300] = {0};
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
int len1 = strlen(str1);
int len2 = strlen(str2);
int max = 0;
int count = 0;
for(int i = 0; i < len1; i++) //输出开头
{
for(int j = 0;j < len2; j++)
{
count = 0;
while(str1[i+count] == str2[j+count] && str1[i+count] != '\0')
{
count++;
}
if(max < count)
{
max = count; //输出结尾
//printf("i:[%d], max:[%d], str1:[%s]\n", i, max, str1+i);
strcpy(out, str1+i);
out[max] = '\0';
}
}
}
printf("%s\n", out);
return 0;
}
示例:
str1 = abcdefghijklmnop
str2 = abcsafjklmnopqrstuvw
/*
i 表示从哪个位置开始
max 表示有几个字符符合要求
*/
i:[0], max:[3], str1:[abcdefghijklmnop]
i:[9], max:[7], str1:[jklmnop]
jklmnop