1092. Shortest Common Supersequence
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.
(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)
Example 1:
Input: str1 = “abac”, str2 = “cab”
Output: “cabac”
Explanation:
str1 = “abac” is a substring of “cabac” because we can delete the first “c”.
str2 = “cab” is a substring of “cabac” because we can delete the last “ac”.
The answer provided is the shortest such string that satisfies these properties.
Note:
- 1 <= str1.length, str2.length <= 1000
- str1 and str2 consist of lowercase English letters.
方法1:
reduce to LCS。
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int m = str1.size(), n = str2.size();
string lcs, res;
vector<vector<string>> dp(m + 1, vector<string>(n + 1, ""));
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + str1[i - 1];
}
else {
dp[i][j] = dp[i - 1][j].size() > dp[i][j - 1].size() ? dp[i - 1][j] : dp[i][j - 1];
}
}
}
lcs = dp.back().back();
int p1 = 0, p2 = 0, p = 0;
while (p1 < m && p2 < n) {
if (lcs[p] == str1[p1] && lcs[p] == str2[p2]) { res += str1[p1]; p1++; p2++; p++; continue;}
if (lcs[p] != str1[p1]) { res += str1[p1]; p1++; }
if (lcs[p] != str2[p2]) { res += str2[p2]; p2++; }
}
if (p1 < m) res += str1.substr(p1);
if (p2 < n) res += str2.substr(p2);
return res;
}
};