HHU数据结构第一次实验Homework
该题目主要涉及字符串操作和动态规划
效果如图:
具体代码实现如下:
#include <algorithm>
#include <iostream>
using namespace std;
string longestCommonStr(string test1, string test2) {
int n = test1.size(), m = test2.size();
int len = 0, res = 0;
int row = 0, col = m - 1; // 从右上角开始
int lcs_i = 0, lcs_j = 0;
// 计算矩阵中的每一条斜线上的值
while (row < n) {
int i = row, j = col; // 斜线起点
while (i < n && j < m) { // 遍历当前斜线
if (test1[i] == test2[j]) {
len++;
if (len > res) {
res = len;
lcs_i = i, lcs_j = j; // 记录最大长度子串的最后一个元素(i,j)
}
}
else len = 0; // 断开后,len重新算
i++, j++;
}
len = 0; // 下一条斜线 len 从 0 开始
// 改变斜线起点
if (col > 0) col--;
else row++;
}
string Result;
row = lcs_i, col = lcs_j;
while (row >= 0 && col >= 0) {
if (test1[row] == test2[col]) Result += test1[row];
else break;
row--, col--;
}
reverse(Result.begin(), Result.end());
if (res == 0)
{
cout << "不存在该子串:" << endl;
return "-1";
}
else
{
cout << "最长子串为:" << endl;
return Result;
}
}
int main() {
string a, b;
cout << "分别开始对子串1和子串2赋值:\n" << endl;
cin >> a >> b;
cout << '\n';
cout << longestCommonStr(a, b);
return 0;
}