题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include "stdio.h"
#include "string.h"
int main()
{
char buf1[500],buf2[500];
while(fgets(buf1,500,stdin))
{
int count=0,max=0;
char *maxprt;
fgets(buf2,500,stdin);
if(strlen(buf1)>strlen(buf2))//选择较短子串为str1
{
char temp[1000];
strcpy(temp,buf1);
strcpy(buf1,buf2);
strcpy(buf2,temp);
}
int len1 = strlen(buf1);
int len2 = strlen(buf2);
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(buf1[i] == buf2[j])
{
count =0;
while(1)
{
if(j+count<len2 && i+count<len1 && buf1[i+count] == buf2[j+count])
{
count++;
}
else
{
if(count>max)
{
maxprt = &buf1[i];
max =count;
}
break;
}
}
}
}
}
char temp[300];
memcpy(temp, maxprt, max);
temp[max] = '\0';
printf("%s\n",temp);
}
return 0;
}
真暴力 真无脑啊