|
| 1 | +// Time: O(m * n) |
| 2 | +// Space: O(m * n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + string shortestCommonSupersequence(string str1, string str2) { |
| 7 | + vector<vector<int>> dp(2, vector<int>(str2.size() + 1)); |
| 8 | + vector<vector<tuple<int, int, char>>> bt(str1.size() + 1, |
| 9 | + vector<tuple<int, int, char>>(str2.size() + 1)); |
| 10 | + for (int i = 0; i < str1.length(); ++i) { |
| 11 | + bt[i + 1][0] = {i, 0, str1[i]}; |
| 12 | + } |
| 13 | + for (int j = 0; j < str2.length(); ++j) { |
| 14 | + bt[0][j + 1] = {0, j, str2[j]}; |
| 15 | + } |
| 16 | + for (int i = 0; i < str1.length(); ++i) { |
| 17 | + for (int j = 0; j < str2.length(); ++j) { |
| 18 | + if (dp[i % 2][j + 1] > dp[(i + 1) % 2][j]) { |
| 19 | + dp[(i + 1) % 2][j + 1] = dp[i % 2][j + 1]; |
| 20 | + bt[i + 1][j + 1] = {i, j + 1, str1[i]}; |
| 21 | + } else { |
| 22 | + dp[(i + 1) % 2][j + 1] = dp[(i + 1) % 2][j]; |
| 23 | + bt[i + 1][j + 1] = {i + 1, j, str2[j]}; |
| 24 | + } |
| 25 | + if (str1[i] != str2[j]) { |
| 26 | + continue; |
| 27 | + } |
| 28 | + if (dp[i % 2][j] + 1 > dp[(i + 1) % 2][j + 1]) { |
| 29 | + dp[(i + 1) % 2][j + 1] = dp[i % 2][j] + 1; |
| 30 | + bt[i + 1][j + 1] = {i, j, str1[i]}; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + int i = str1.length(), j = str2.length(); |
| 36 | + char c = 0; |
| 37 | + string result; |
| 38 | + while (i != 0 || j != 0) { |
| 39 | + tie(i, j, c) = bt[i][j]; |
| 40 | + result.push_back(c); |
| 41 | + } |
| 42 | + reverse(result.begin(), result.end()); |
| 43 | + return result; |
| 44 | + } |
| 45 | +}; |
0 commit comments