最长公共子序列不要求连续
代码
#include<iostream>
#include<vector>
using namespace std;
void printTheLCS(string& str1, string& str2, vector<vector<int> > path, int first, int second)
{
if(first==0||second==0)
return ;
if(path[first][second]==1)
{
printTheLCS(str1, str2, path, first-1, second-1);
cout << str1[first-1];
}
else if(path[first][second]==2)
{
printTheLCS(str1, str2, path, first, second-1);
}
else
{
printTheLCS(str1, str2, path, first-1, second);
}
}
// 1 代表左上方, 2 代表 左方, 3 代表右方
void LCS(string& str1, string &str2)
{
int len1 = str1.length();
int len2 = str2.length();
vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));
vector<vector<int> > path(len1+1, vector<int>(len2+1, 0));
for(int i = 1; i <= len1; ++i)
for(int j = 1; j <= len2; ++j)
{
if(str1[i-1]==str2[j-1])
{
dpLongest[i][j] = dpLongest[i-1][j-1] + 1;
path[i][j] = 1;
}
else if(dpLongest[i][j-1]>=dpLongest[i-1][j])
{
dpLongest[i][j] = dpLongest[i][j-1];
path[i][j] = 2;
}
else
{
dpLongest[i][j] = dpLongest[i-1][j];
path[i][j] = 3;
}
}
cout << "The length of the LCS is:" << dpLongest[len1][len2] << endl;
cout << "The LCS is:";
printTheLCS(str1, str2, path, len1, len2);
cout << endl;
}
int main()
{
string str1, str2;
str1 = "abcd";
str2 = "bacd";
LCS(str1, str2);
return 1;
}
最长公共字串要求连续
代码
#include<iostream>
#include<vector>
using namespace std;
void LCSContinuous(string& str1, string &str2)
{
int len1 = str1.length();
int len2 = str2.length();
vector<vector<int> > dpLongest(len1+1, vector<int>(len2+1, 0));
int maxLen = 0;
int maxIndex = 0;
for(int i = 0; i < len1; ++i)
for(int j = 0; j < len2; ++j)
{
if(str1[i]==str2[j])
{
if(i&&j)
dpLongest[i][j] = dpLongest[i-1][j-1] + 1;
if(i==0||j==0)
dpLongest[i][j] = 1;
if(dpLongest[i][j]>maxLen)
{
maxLen = dpLongest[i][j];
maxIndex = i - maxLen + 1;
}
}
}
cout << "The length of the LCS is:" << maxLen << endl;
cout << "The LCS is:";
int i = maxIndex;
while(maxLen)
{
cout << str1[i++];
maxLen--;
}
cout << endl;
}
int main()
{
string str1, str2;
str1 = "abcd";
str2 = "bacd";
LCSContinuous(str1, str2);
return 1;
}