Monday, August 24, 2020

LeetCode [1092] Shortest Common Supersequence

 1092. Shortest Common Supersequence

Hard

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.)

 

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.

 

Note:

  1. 1 <= str1.length, str2.length <= 1000
  2. str1 and str2 consist of lowercase English letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
    public String shortestCommonSupersequence(String str1, String str2) {
        String lcStr = lcs(str1, str2);
        int i = 0, j = 0;
        String tmp = "";
        for(char c: lcStr.toCharArray()){
            while(str1.charAt(i)!=c){
                tmp += str1.charAt(i);
                i++;
            }
            while(str2.charAt(j)!=c){
                tmp += str2.charAt(j);
                j++;
            }
            tmp += c;
            i++;
            j++;
        }
        return tmp + str1.substring(i) + str2.substring(j);
    }

    String lcs(String str1, String str2){
        int m = str1.length(), n = str2.length();
        String[][] dp = new String[m+1][n+1];
        for(int i=0; i<=m; ++i) Arrays.fill(dp[i], "");
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(str1.charAt(i)==str2.charAt(j)){
                    dp[i+1][j+1] = dp[i][j]+str1.charAt(i);
                }else{
                    if(dp[i+1][j].length()>dp[i][j+1].length()){
                        dp[i+1][j+1] = dp[i+1][j];
                    }else{
                        dp[i+1][j+1] = dp[i][j+1];
                    }
                }
            }
        }
        return dp[m][n];
    }
}

No comments:

Post a Comment