1092. Shortest Common Supersequence #1373
-
Topics: Given two strings A string Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the shortest common supersequence (SCS) of two given strings. The SCS is the shortest string that contains both input strings as subsequences. The approach involves using dynamic programming (DP) to determine the longest common subsequence (LCS) and then constructing the SCS by merging the two input strings based on the LCS. Approach
Let's implement this solution in PHP: 1092. Shortest Common Supersequence <?php
/**
* @param String $str1
* @param String $str2
* @return String
*/
function shortestCommonSupersequence($str1, $str2) {
$m = strlen($str1);
$n = strlen($str2);
// Create a DP table to store lengths of the longest common subsequence.
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
// Fill the DP table.
for ($i = 1; $i <= $m; $i++) {
for ($j = 1; $j <= $n; $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]);
}
}
}
$i = $m;
$j = $n;
$result = array();
// Backtrack to build the shortest common supersequence.
while ($i > 0 && $j > 0) {
if ($str1[$i - 1] == $str2[$j - 1]) {
array_push($result, $str1[$i - 1]);
$i--;
$j--;
} else {
if ($dp[$i - 1][$j] >= $dp[$i][$j - 1]) {
array_push($result, $str1[$i - 1]);
$i--;
} else {
array_push($result, $str2[$j - 1]);
$j--;
}
}
}
// Add remaining characters from str1.
while ($i > 0) {
array_push($result, $str1[$i - 1]);
$i--;
}
// Add remaining characters from str2.
while ($j > 0) {
array_push($result, $str2[$j - 1]);
$j--;
}
// Reverse to get the correct order.
$result = array_reverse($result);
return implode('', $result);
}
// Example Cases
echo shortestCommonSupersequence("abac", "cab") . "\n"; // Output: "cabac"
echo shortestCommonSupersequence("aaaaaaaa", "aaaaaaaa") . "\n"; // Output: "aaaaaaaa"
?> Explanation:
This approach efficiently constructs the shortest common supersequence by leveraging the LCS, ensuring that the solution is both optimal and correct. |
Beta Was this translation helpful? Give feedback.
We need to find the shortest common supersequence (SCS) of two given strings. The SCS is the shortest string that contains both input strings as subsequences. The approach involves using dynamic programming (DP) to determine the longest common subsequence (LCS) and then constructing the SCS by merging the two input strings based on the LCS.
Approach
Dynamic Programming (DP) Table Construction:
dp[i][j]
represents the length of the LCS of the substringsstr1[0..i-1]
andstr2[0..j-1]
.Backtracking to Construct SCS: