【最长公共子串代码】
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxSize 100
typedef struct
{
char ch[maxSize];
int length;
}Str;
//若s[i]==s[j],用L[i][j]表示以s1[i]和s2[j]结尾的相同子串长度,记为L[i][j] = L[i-1][j-1] + 1
void CommonStr(Str s1,Str s2)
{
int maxlen, mi, mj;
int i,j;
int L[maxSize][maxSize];
maxlen = 0;
//初始化L数组,因为L[i][0]和L[0][j]不能直接通过迭代即L[i][j] = L[i-1][j-1] + 1得到
for (i = 0; i < s1.length; ++i)
{
if (s1.ch[i] == s2.ch[0])
L[i][0] = 1;
else
L[i][0] = 0;
}
for (j = 0; j < s2.length; ++j)
{
if (s2.ch[j] == s1.ch[0])
L[0][j] = 1;
else
L[0][j] = 0;
}
for (i = 1; i < s1.length; ++i)
{
for (j = 1; j < s2.length; ++j)
{
if (s1.ch[i] == s2.ch[j])
{
L[i][j] = L[i - 1][j - 1] + 1;
}
else
{
L[i][j] = 0;//由于一开始没有初始化数组中其他值,所以必须加上这一行代码
}
if (L[i][j] > maxlen)
{
maxlen = L[i][j];
mi = i - maxlen + 1;
mj = j - maxlen + 1;
}
}
}
printf("最长公共子串为:");
for (i = 0; i < maxlen; ++i)
{
printf("%c", s1.ch[i + mi]);
}
printf("\n");
printf("长度:%d\n在s1中的位置:%d\n在s2中的位置:%d", maxlen, mi, mj);
}
int main()
{
Str s1, s2;
char s[maxSize] = "abcdefg";
char t[maxSize] = "xxxxxcdefxxxx";
strcpy(s1.ch, s);
strcpy(s2.ch, t);
s1.length = strlen(s1.ch);
s2.length = strlen(s2.ch);
CommonStr(s1, s2);
return 0;
}
【最长公共子序列】
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#define maxSize 100
int CommonString(char s1[], char s2[])
{
int a[maxSize][maxSize];
int n1, n2;
int i, j;
int max;
n1 = strlen(s1);
n2 = strlen(s2);
for (i = 0; i < n1; ++i)
{
if (s1[0] == s2[i])
{
a[0][i] = 1;
}
else
{
a[0][i] = 0;
}
}
for (i = 0; i < n1; ++i)
{
if (s1[i] == s2[0])
{
a[i][0] = 1;
}
else
{
a[i][0] = 0;
}
}
max = 0;
for (i = 1; i < n1; ++i)
for (j = 1; j < n2; ++j)
{
if (s1[i] == s2[j])
{
a[i][j] = a[i - 1][j - 1] + 1;
}
else
{
a[i][j] = a[i - 1][j] > a[i][j - 1] ? a[i - 1][j]: a[i][j - 1];
}
if (a[i][j] > max)
{
max = a[i][j];
}
}
return max;
}
int main()
{
char s1[100] = "13542687", s2[100] = "148675";
printf("%d",CommonString(s1, s2));
return 0;
}