题目描述
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 subsequence of “cabac” because we can delete the first “c”.
str2 = “cab” is a subsequence 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.
思路
由最长公共子序列构成。
先用动态规划求出两个字符串的最长公共序列,然后在公共序列中按序插入两个字符串中的其它字符。
代码
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int l1 = str1.length();
int l2 = str2.length();
vector<vector<int>> dp(l1+1, vector<int>(l2+1, 0));
for (int i=1; i<=l1; ++i) {
for (int j=1; j<=l2; ++j) {
if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
string res = "";
while(l1 || l2) {
char cur;
if (l1 == 0) cur = str2[--l2];
else if (l2 == 0) cur = str1[--l1];
else if (str1[l1-1] == str2[l2-1]) cur = str1[--l1] = str2[--l2];
else if (dp[l1-1][l2] == dp[l1][l2]) cur = str1[--l1];
else if (dp[l1][l2-1] == dp[l1][l2]) cur = str2[--l2];
res = cur + res;
}
return res;
}
};