题解 | 最长公共子序列(二)
最长公共子序列(二)
https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
#include <iterator>
#include <string>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
string LCS(string s1, string s2) {
// write code here
if (s1.empty() || s2.empty()) {
return "-1";
}
int n = s1.size();
int m = s2.size();
s1 = " " + s1;
s2 = " " + s2;
vector<vector<int>> dp(n + 1, vector<int> (m + 1,0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s1[i] == s2[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
if (dp[n][m] == 0) {
return "-1";
}
string ret;
//咋瓦鲁多,时空回溯~
int i = n;
int j = m;
while (i > 0 && j > 0)
{
if (s1[i] == s2[j])
{
ret+=s1[i];
i--;
j--;
}
else
{
if (dp[i - 1][j] > dp[i][j - 1])
{
i--;
}
else
{
j--;
}
}
}
reverse(ret.begin(),ret.end());
return ret;
}
};
