Skip to content

Double Sequence IX

Description

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.

(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

  • Note:
  • 1 <= str1.length, str2.length <= 1000
  • str1 and str2 consist of lowercase English letters.

https://leetcode.com/problems/shortest-common-supersequence/description/

Example I:

Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.

Example II:

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.

Questions

  • LeetCode - 1092. Shortest Common Supersequence

Transform Function

for(int i = 1; i <= m; i++) {
    for(int j = 1; j <= n; j++) {
        if(c1[i - 1] == c2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1];
        else {
            dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
        }
    }
}

Solution I

class Solution {
    public String shortestCommonSupersequence(String str1, String str2) {
        char[] c1 = str1.toCharArray(), c2 = str2.toCharArray();
        int m = c1.length, n = c2.length;
        int[][] dp = new int[m + 1][n + 1];
        for(int i = 0; i <= m; i++) dp[i][0] = i;
        for(int j = 0; j <= n; j++) dp[0][j] = j;

        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                if(c1[i - 1] == c2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1];
                else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        int l = dp[m][n];
        char[] arr = new char[l];
        int i = m, j = n;
        while(i > 0 && j > 0) {
            if(c1[i - 1] == c2[j - 1]) {
                arr[--l] = c1[i - 1];
                i--;
                j--;
            }else if(dp[i - 1][j] < dp[i][j - 1]){
                arr[--l] = c1[i - 1];
                i--;
            }else{
                arr[--l] = c2[j - 1];
                j--;
            }
        }
        while (i > 0) {
            arr[--l] = c1[i - 1];
            i--;
        }
        while (j > 0) {
            arr[--l] = c2[j - 1];
            j--;
        }
        return new String(arr);
    }
}