LeetCode 1092. 最短公共超序列

3 篇文章 0 订阅

1092. 最短公共超序列

 

 【DP】这道题是1143. 最长公共子序列剑指 Offer II 095. 最长公共子序列的加强版。

class Solution {
    public String shortestCommonSupersequence(String str1, String str2) {
        int m = str1.length(), n = str2.length();
        int[][]dp = new int[m + 1][n + 1];
        String[][] strs = new String[m + 1][n + 1];
        for (int i = 0; i < m; i++) strs[i][0] = "";
        for (int i = 0; i < n; i++) strs[0][i] = "";
        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;
                    strs[i][j] = strs[i - 1][j - 1] + str1.charAt(i - 1);
                }
                else {
                    if (dp[i - 1][j] > dp[i][j - 1]) {
                        strs[i][j] = strs[i - 1][j];
                    } else {
                        strs[i][j] = strs[i][j - 1];
                    }
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);

                }
            }
        }
        String common = strs[m][n];
        StringBuilder sb = new StringBuilder();
        int i = 0, j = 0, k = 0, l = common.length();
        while (i < m && j < n) {
            if (k == l) break;
            char c = common.charAt(k);
            if (str1.charAt(i) == c && str2.charAt(j) == c) {
                sb.append(common.charAt(k++));
                i++; j++;
                continue;
            }
            if (str1.charAt(i) != c) {
                sb.append(str1.charAt(i++));
            }
            if (str2.charAt(j) != c) {
                sb.append(str2.charAt(j++));
            }
        }
        while (i < m) sb.append(str1.charAt(i++));
        while (j < n) sb.append(str2.charAt(j++));
        return sb.toString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值