题目:编程实现查找两个字符串的最大公共子串
示例:"aocdfe"和"pmcdfa"最大公共子串为"cdf"
#include <stdio.h>
#include <string.h>
int main() //暴力破解
//缺点:子串较长时,重复比较 子串 及 子串的所有子串(cdf c d f cd df 都会比较一遍 )
{
char *str1 = "aocdfe";
char *str2 = "aadapmcdfa";
int longest = 0; // 最大长度
int i,j;
int start = 0;
for (i = 0; i < strlen(str1); i++)
{
for (j = 0; j < strlen(str2); j++)
{
int len = 0;
if (str1[i] == str2[j])
{
int a, b;
for (a = i, b = j; a<strlen(str1) && b<strlen(str2); a++, b++)
{
if (str1[a] == str2[b])
len++;
else
break;
}
}
if (len > longest)
{
longest = len;
start = i;
}
}
}
for (i = start; i < longest+start; i++)
printf ("%c", str1[i]);
printf ("\n");
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
char *str1 = "aodacdfe"; //c cd cdf cdfe
char *str2 = "aadapmcdfea"; //c cd cdf cdfe
//1 2 3 4
int table[100][100] = {0}; //c d f e
//创建一个二维数组用于存放长度 //f(n) = f(n-1) + 1
int i;
int j;
for (i = 0; i < strlen(str2); i++)
{
if (str1[0] == str2[i]) //确定初值f(0)
table[0][i] = 1;
else
table[0][i] = 0;
}
for (i = 1; i < strlen(str1); i++) //将二维数组填满,所有公共子串长度都可以得到
{
if (str2[0] == str1[i]) //确定初值f(0)
table[i][0] = 1;
else
table[i][0] = 0;
for (j = 1; j < strlen(str2); j++)
{
if (str1[i] == str2[j])
{
table[i][j] = table[i-1][j-1] + 1; //f(n) = f(n-1) + 1
}
else
{
table[i][j] = 0;
}
}
}
int start = 0;
int longest = table[0][0];
for (i = 1; i < strlen(str1); i++) //遍历二维数组,找出其中最长的长度,记下下标
{
for (j = 1; j < strlen(str2); j++)
{
if (longest < table[i][j])
{
longest = table[i][j];
start = i - longest + 1;
}
}
}
printf ("最大长度是:%d\n", longest);
for (i = start; i < longest+start; i++) //根据下标及长度打印出最大公共子串
{
printf ("%c", str1[i]);
}
printf ("\n");
return 0;
}