【LeetCode 1092】 Shortest Common Supersequence

题目描述

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 <= str1.length, str2.length <= 1000
str1 and str2 consist of lowercase English letters.

思路

由最长公共子序列构成。
先用动态规划求出两个字符串的最长公共序列,然后在公共序列中按序插入两个字符串中的其它字符。

代码

class Solution {
public:
    string shortestCommonSupersequence(string str1, string str2) {
        int l1 = str1.length();
        int l2 = str2.length();
        vector<vector<int>> dp(l1+1, vector<int>(l2+1, 0));
        
        for (int i=1; i<=l1; ++i) {
            for (int j=1; j<=l2; ++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]);
            }
        }
        
        string res = "";
        while(l1 || l2) {
            char cur;
            if (l1 == 0) cur = str2[--l2];
            else if (l2 == 0) cur = str1[--l1];
            else if (str1[l1-1] == str2[l2-1]) cur = str1[--l1] = str2[--l2];
            else if (dp[l1-1][l2] == dp[l1][l2]) cur = str1[--l1];
            else if (dp[l1][l2-1] == dp[l1][l2]) cur = str2[--l2];
            res = cur + res;
        }
        
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值