给定两个序列 X 和Y ,如果Z既是X的子序列又是Y的子序列,我们称它是公共子序列。
设定 c[i][j]表示Xi与Yi公共子序列个数则
c[i][j] | result | i,j |
---|---|---|
c[i][j]= | 0 | i=0或j=0 |
c[i][j]= | c[i-1][j-1]+1 | i,j>0 且Xi=Yj |
c[i][j]= | max(c[i-1][j],c[i][j-1]) | i,j>0 且Xi!=Yj |
#include<iostream>
#include <string>
const int max = 100;
char result[max];//存放公共子序列
using namespace std;
int LCS_LENGTH(string x, string y,int b[max][max],int,int);//返回最长公共子序列长度
void Display_Lcs(int i, int j, string x, int b[][max], int current_Len); //输出公共序列
int main()
{
string x = "ABCBDAB";
string y = "ABCB";
int lengthx = x.size();
int lengthy = y.size();
int b[max][max];
int length = LCS_LENGTH(x, y,b,lengthx,lengthy);
cout << length << endl;
Display_Lcs(lengthx, lengthy, x, b, length);
for (int i = 0; i < length; i++)
{
cout << result[i] << ' ';
}
system("pause");
}
int LCS_LENGTH(string x, string y,int b[max][max],int lengthx,int lengthy)
{
int c[max][max];//保存x 和y的LCS长度
int i = 0;int j = 0;
for (i = 0; i <= lengthx; i++)
{
c[i][0] = 0; //若其中字符串x没有字符公共长度为0;
}
for (j = 0; j <= lengthy; j++)
{
c[0][j] = 0; //若其中字符串y没有字符公共长度为0;
}
for (i = 1; i <= lengthx; i++)
{
for (j = 1; j <= lengthy; j++)
{
if (x[i - 1] == y[j - 1])
{
c[i][j] = c[i - 1][j - 1] + 1;//如果Xm 和Yn相等则 应求解 Xm-1和Yn-1的公共序列
b[i][j] = 1;
}
else
if (c[i - 1][j] > c[i][j - 1]) //如果Xm 和Yn不相等则 应求解 Xm - 1和Yn 的公共序列 与Xm 和Yn-1的公共序列
{
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
else
if (c[i - 1][j] <= c[i][j - 1])
{
c[i][j] = c[i][j - 1];
b[i][j] = 3;
}
}
}
for( i=1;i<=lengthx;i++)
for (j = 1; j <= lengthy; j++)
{
cout << c[i][j] << ' ';
}
return c[lengthx][lengthy];
}
void Display_Lcs(int i, int j, string x, int b[][max], int current_Len)
{
if (i == 0 || j == 0)
{
return;
}
if (b[i][j] == 1)
{
current_Len--;
result[current_Len] = x[i - 1];
Display_Lcs(i - 1, j - 1, x, b, current_Len);
}
else
{
if (b[i][j] == 2)
{
Display_Lcs(i - 1, j, x, b, current_Len);
}
else
{
if (b[i][j] == 3)
{
Display_Lcs(i, j - 1, x, b, current_Len);
}
else
{
Display_Lcs(i - 1, j, x, b, current_Len);
}
}
}
}