LeetCode 1092. 最短公共超序列 Printing
2019-06-16 本文已影响0人
独孤岳
给出两个字符串 str1
和 str2
,返回同时以 str1
和 str2
作为子序列的最短字符串。如果答案不止一个,则可以返回满足条件的任意一个答案。
(如果从字符串 T 中删除一些字符(也可能不删除,并且选出的这些字符可以位于 T 中的 任意位置),可以得到字符串 S,那么 S 就是 T 的子序列)
示例:
输入:str1 = "abac", str2 = "cab"
输出:"cabac"
解释:
str1 = "abac" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 的第一个 "c"得到 "abac"。
str2 = "cab" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 末尾的 "ac" 得到 "cab"。
最终我们给出的答案是满足上述属性的最短字符串。
提示:
1 <= str1.length, str2.length <= 1000
-
str1
和str2
都由小写英文字母组成。
思路:
Printing Shortest Common Supersequence
代码:
class Solution {
public:
string shortestCommonSupersequence(string X, string Y) {
int m = X.length();
int n = Y.length();
// dp[i][j] contains length of shortest supersequence
// for X[0..i-1] and Y[0..j-1]
int dp[m + 1][n + 1];
// Fill table in bottom up manner
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
// Below steps follow recurrence relation
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(X[i - 1] == Y[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]);
}
}
// Following code is used to print shortest supersequence
// dp[m][n] stores the length of the shortest supersequence
// of X and Y
int index = dp[m][n];
// string to store the shortest supersequence
string str;
// Start from the bottom right corner and one by one
// push characters in output string
int i = m, j = n;
while (i > 0 && j > 0)
{
// If current character in X and Y are same, then
// current character is part of shortest supersequence
if (X[i - 1] == Y[j - 1])
{
// Put current character in result
str.push_back(X[i - 1]);
// reduce values of i, j and index
i--, j--, index--;
}
// If current character in X and Y are different
else if (dp[i - 1][j] > dp[i][j - 1])
{
// Put current character of Y in result
str.push_back(Y[j - 1]);
// reduce values of j and index
j--, index--;
}
else
{
// Put current character of X in result
str.push_back(X[i - 1]);
// reduce values of i and index
i--, index--;
}
}
// If Y reaches its end, put remaining characters
// of X in the result string
while (i > 0)
{
str.push_back(X[i - 1]);
i--, index--;
}
// If X reaches its end, put remaining characters
// of Y in the result string
while (j > 0)
{
str.push_back(Y[j - 1]);
j--, index--;
}
// reverse the string and return it
reverse(str.begin(), str.end());
return str;
}
};