题目描述:
给出两个字符串 str1 和 str2,返回同时以 str1 和 str2 作为子序列的最短字符串。如果答案不止一个,则可以返回满足条件的任意一个答案。(如果从字符串 T 中删除一些字符(也可能不删除,并且选出的这些字符可以位于 T 中的 任意位置),可以得到字符串 S,那么 S 就是 T 的子序列)
链接:https://leetcode-cn.com/problems/shortest-common-supersequence
解题思路:
- 先找最长公共子序列
- 再用一个三指针进行遍历
typedef pair<int, string> Ele;class Solution {public:string shortestCommonSupersequence(string str1, string str2) {int len1=str1.length(), len2=str2.length();vector<vector<Ele>> dp(len1+1, vector<Ele>(len2+1, Ele(0, "")));for (int i=1; i<=len1; i++) {for (int j=1; j<=len2; j++) {if (str1[i-1]==str2[j-1]) {dp[i][j].first=dp[i-1][j-1].first+1;dp[i][j].second=dp[i-1][j-1].second+string(1, str1[i-1]);} else {if (dp[i-1][j].first > dp[i][j-1].first) {dp[i][j]=dp[i-1][j];}else {dp[i][j]=dp[i][j-1];}}}}string comm_str=dp[len1][len2].second;//cout << comm_str;int i=0, j=0, k=0;string ret="";while (k<comm_str.length()) {char comm_ch=comm_str[k];while (str1[i] != comm_ch) {ret += string(1, str1[i]);i++;}while (str2[j] != comm_ch) {ret += string(1, str2[j]);j++;}ret += string(1, comm_ch);i++;j++;k++;}while (i<len1)ret += string(1, str1[i++]);while (j<len2)ret += string(1, str2[j++]);return ret;}};
