class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size();
int n = text2.size();
if (!m || !n)
return 0;
vector<vector<int> > dp(m+1, vector<int>(n+1, 0));
// dp[0][0] = (s1[0] == s2[0]);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1[i-1] == text2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i][j-1]));
}
}
}
return dp[m][n];
}
};
直接将 int 换成 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
int m = s1.size();
int n = s2.size();
vector<vector<string> > dp(m+1, vector<string>(n+1, ""));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i-1] == s2[j-1]) {
dp[i][j] = dp[i-1][j-1] + s1[i-1];
} else {
dp[i][j] = dp[i-1][j].length() > dp[i][j-1].length() ? dp[i-1][j] : dp[i][j-1];
}
}
}
return dp[m][n].empty() ? "-1" : dp[m][n];
}
};
正确的做法
#include <iterator>
#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
int m = s1.size();
int n = s2.size();
if (!m || !n)
return "-1";
vector<vector<int> > dp(m + 1, vector<int>(n + 1, 0));
// dp[0][0] = (s1[0] == s2[0]);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j - 1], max(dp[i - 1][j], dp[i][j - 1]));
}
}
}
int i = m, j = n;
string ans;
while (dp[i][j]) {
if (dp[i-1][j] == dp[i][j-1] && dp[i][j] > dp[i-1][j-1]) {
ans += s1[i-1];
i--;
j--;
} else if (dp[i-1][j] > dp[i][j-1]) { //向数字大的方向走
i--;
} else j--;
}
reverse(ans.begin(), ans.end());
return ans == "" ? "-1" : ans;
}
};
要解决的关键是如何回溯出原来的字符串。
参考资料:https://blog.csdn.net/haizi8888/article/details/23214151?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%2223214151%22%2C%22source%22%3A%22weixin_51187533%22%7D