LeetCode 1092: Shortest Common Supersequence Solution
Master LeetCode problem 1092 (Shortest Common Supersequence ), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1092. Shortest Common Supersequence
Problem Explanation
Explanation
To find the shortest common supersequence of two strings, we can use dynamic programming. Let dp[i][j] represent the length of the shortest common supersequence of str1[0...i-1] and str2[0...j-1]. We can build this table by considering the following cases:
- If the characters at the current positions are equal, then the current character is part of the supersequence. So,
dp[i][j] = dp[i-1][j-1] + 1. - If the characters are different, we have two options: either include
str1[i-1]in the supersequence orstr2[j-1]. So,dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1.
Finally, to reconstruct the shortest common supersequence, we can start from dp[m][n] and backtrack by considering the characters and transitions made during the dp table construction.
Solution Code
class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + 1;
}
}
}
StringBuilder sb = new StringBuilder();
int i = m, j = n;
while (i > 0 && j > 0) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
sb.insert(0, str1.charAt(i-1));
i--;
j--;
} else if (dp[i-1][j] < dp[i][j-1]) {
sb.insert(0, str1.charAt(i-1));
i--;
} else {
sb.insert(0, str2.charAt(j-1));
j--;
}
}
while (i > 0) {
sb.insert(0, str1.charAt(i-1));
i--;
}
while (j > 0) {
sb.insert(0, str2.charAt(j-1));
j--;
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1092 (Shortest Common Supersequence )?
This page provides optimized solutions for LeetCode problem 1092 (Shortest Common Supersequence ) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1092 (Shortest Common Supersequence )?
The time complexity for LeetCode 1092 (Shortest Common Supersequence ) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1092 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1092 in Java, C++, or Python.