Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.
A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) 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.
Example 2:
Input: str1 = “aaaaaaaa”, str2 = “aaaaaaaa”
Output: “aaaaaaaa”
Constraints:
1 <= str1.length, str2.length <= 1000str1andstr2consist of lowercase English letters.Given two stringsstr1andstr2, return the shortest string that has bothstr1andstr2as subsequences. If there are multiple valid strings, return any of them.
A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) 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.
Example 2:
Input: str1 = “aaaaaaaa”, str2 = “aaaaaaaa”
Output: “aaaaaaaa”
Constraints:
1 <= str1.length, str2.length <= 1000str1andstr2consist of lowercase English letters.
Approach - Bottom Up
- Follow the same logic but could be reverse
O(m*n), O(m*n)
class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
int m = str1.length(), n = str2.length();
int[][] dp = new int[m+1][n+1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
dp[i][j] = i+j;
else if (str1.charAt(i-1) == str2.charAt(j-1))
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = 1 + Math.min(dp[i][j-1], dp[i-1][j]);
}
}
StringBuilder ans = new StringBuilder();
int i = m, j = n;
while (i > 0 && j > 0) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
ans.append(str1.charAt(i-1));
i--;
j--;
} else if (dp[i-1][j] < dp[i][j-1]) {
ans.append(str1.charAt(i-1));
i--;
} else {
ans.append(str2.charAt(j-1));
j--;
}
}
while (i > 0) {
ans.append(str1.charAt(i-1));
i--;
}
while (j > 0) {
ans.append(str2.charAt(j-1));
j--;
}
return ans.reverse().toString();
}
}Approach - Recursion
- This code is for to just find the length
class Solution {
public int shortestCommonSupersequence(String str1, String str2) {
return dfs(str1, str2, 0, 0);
}
private int dfs(String s1, String s2, int i, int j) {
if (i == s1.length() || j == s2.length())
return i + j;
if (s1.charAt(i) == s2.charAt(j))
return 1 + dfs(s1, s2, i+1, j+1);
else
return 1 + Math.min(dfs(s1,s2,i+1,j),dfs(s1,s2,i,j+1));
}
}