题解 | 最长公共子序列(二)
最长公共子序列(二)
https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
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 len1 = s1.length(), len2 = s2.length(); string ans; if (len1 == 0 || len2 == 0) { return "-1"; } vector<vector<int>>dp(len1 + 1, vector<int>(len2 + 1, 0)); for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { dp[i][j] = 0; } } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; 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], dp[i][j - 1]); } } } int a = len1, b = len2; while(dp[a][b]>0){ if(dp[a][b]>dp[a][b-1]&&dp[a][b]>dp[a-1][b]){ ans += s1[a-1]; b--; a--; continue; } if(dp[a][b] == dp[a][b-1]){ b--; continue; } if(dp[a][b] == dp[a-1][b]){ a--; continue; } } reverse(ans.begin(),ans.end()); if(ans.length()<1){ return "-1"; } return ans; } };#动态规划#