Skip to content

Commit f0bd5e7

Browse files
committed
Solution #1092 - Mridul/Edited - 01/03/2025
1 parent aa03332 commit f0bd5e7

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

DP/#1092 - Shortest Common Supersequence - Hard/Shortest Common Supersequence - Explanation.md

Whitespace-only changes.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public String shortestCommonSupersequence(String str1, String str2) {
3+
int m = str1.length();
4+
int n = str2.length();
5+
6+
// Create DP table
7+
int[][] dp = new int[m + 1][n + 1];
8+
9+
// Fill the DP table
10+
for (int i = 1; i <= m; i++) {
11+
for (int j = 1; j <= n; j++) {
12+
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
13+
dp[i][j] = dp[i - 1][j - 1] + 1; // If characters match
14+
} else {
15+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Take max from either previous row or column
16+
}
17+
}
18+
}
19+
20+
// Build the shortest common supersequence
21+
StringBuilder result = new StringBuilder();
22+
int i = m, j = n;
23+
while (i > 0 && j > 0) {
24+
// If characters are the same, add to the result
25+
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
26+
result.append(str1.charAt(i - 1));
27+
i--;
28+
j--;
29+
} else if (dp[i - 1][j] > dp[i][j - 1]) { // Move in the direction of the larger dp value
30+
result.append(str1.charAt(i - 1));
31+
i--;
32+
} else {
33+
result.append(str2.charAt(j - 1));
34+
j--;
35+
}
36+
}
37+
38+
// If there are any remaining characters in str1
39+
while (i > 0) {
40+
result.append(str1.charAt(i - 1));
41+
i--;
42+
}
43+
44+
// If there are any remaining characters in str2
45+
while (j > 0) {
46+
result.append(str2.charAt(j - 1));
47+
j--;
48+
}
49+
50+
// Reverse the result before returning
51+
return result.reverse().toString();
52+
}
53+
}

0 commit comments

Comments
 (0)