Longest Common Subsequence
C[i,j]=max{C[i,j-1],C[i-1,j]}(x[i]!=y[j])
C[i,j]=Ci-1,j-1
C[i,j]表示x[i],y[j]的LCS的長度。
兩個字符串對應的最長公共子序列不唯一,具體分析見註釋
#include<iostream>
#include<cstring>
#include<set>
#include<cstring>
using namespace std;
set<string>all_lcs;
int c[100][100];
int b[100][100];
void Length (string x, string y);
void PrintAllLCS(string &str1, string &str2, int i, int j, string lcs_str);
int main()
{
string str1,str2;
string lcs_str;
while (cin >> str1 >> str2)
{
Length (str1, str2);
PrintAllLCS(str1, str2,str1.length(), str2.length(), lcs_str);
set<string>::iterator iter=all_lcs.begin();
while(iter!=all_lcs.end())
cout<<*iter++<<'\n';
all_lcs.clear();
}
}
void Length (string x, string y)
{
int m = x.length();
int n = y.length();
for (int i = 0; i <= m; i++)
c[i][0] = 0;
for (int i = 0; i <= n; i++)
c[0][i] = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (x[i] == y[j])
{
c[i + 1][j + 1] = c[i][j] + 1;
}
else if (c[i][j + 1] >= c[i + 1][j])
{
c[i + 1][j + 1] = c[i][j + 1];
}
else if(c[i][j+1]<c[i+1][j])
{
c[i + 1][j + 1] = c[i + 1][j];
}
}
}
}
void PrintAllLCS(string &str1, string &str2, int i, int j, string lcs_str) {
while (i > 0 && j > 0) {
if (str1[i - 1] == str2[j - 1]) {
lcs_str = str1[i - 1] + lcs_str; //逆向存放
--i;
--j;
}
else {
if (c[i - 1][j] > c[i][j - 1]) //向左走
--i;
else if (c[i - 1][j] < c[i][j - 1]) //向上走
--j;
else { //此時向上向右均爲LCS的元素
PrintAllLCS(str1, str2, i - 1, j, lcs_str);
PrintAllLCS(str1, str2, i, j - 1, lcs_str);
return;
}
}
}
all_lcs.insert(lcs_str);
}