/*最长公共子序列C++代码
输入:2个字符串
输出:最长公共子序列长度
最长公共子序列
*/
#include <iostream>
using namespace std;
int main() {
string str1, str2;
int length1, length2;
const int row = 300;
const int col = 300;
int arr[row][col];
cout << "请分别输入两个字符串:";
cin >> str1 >> str2;
length1 = str1.length();
length2 = str2.length();
memset(arr, 0, sizeof(arr));
for (int i = 1; i <= length1; i++) {
for (int j = 1; j <= length2; j++) {
if (str1[i - 1] == str2[j - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
} else {
arr[i][j] = (arr[i - 1][j] > arr[i][j - 1] ? arr[i - 1][j] : arr[i][j - 1]);
}
}
}
cout << arr[length1][length2] << endl;
string print = "";
for (int i = length1, j = length2; i >= 1 && j >= 1;) {
if (str1[i - 1] == str2[j - 1]) {
print = str1[i - 1] + print;
i--;
j--;
} else {
if (arr[i][j - 1] >= arr[i - 1][j])j--;
else
i--;
}
}
cout << print << endl;
return 0;
}
最长公共子序列(LCS)
最新推荐文章于 2022-06-05 08:58:34 发布