题目描述:

给出两个字符串 str1 和 str2,返回同时以 str1 和 str2 作为子序列的最短字符串。如果答案不止一个,则可以返回满足条件的任意一个答案。(如果从字符串 T 中删除一些字符(也可能不删除,并且选出的这些字符可以位于 T 中的 任意位置),可以得到字符串 S,那么 S 就是 T 的子序列)

链接:https://leetcode-cn.com/problems/shortest-common-supersequence

解题思路:

  • 先找最长公共子序列
  • 再用一个三指针进行遍历
    1. typedef pair<int, string> Ele;
    2. class Solution {
    3. public:
    4. string shortestCommonSupersequence(string str1, string str2) {
    5. int len1=str1.length(), len2=str2.length();
    6. vector<vector<Ele>> dp(len1+1, vector<Ele>(len2+1, Ele(0, "")));
    7. for (int i=1; i<=len1; i++) {
    8. for (int j=1; j<=len2; j++) {
    9. if (str1[i-1]==str2[j-1]) {
    10. dp[i][j].first=dp[i-1][j-1].first+1;
    11. dp[i][j].second=dp[i-1][j-1].second+string(1, str1[i-1]);
    12. } else {
    13. if (dp[i-1][j].first > dp[i][j-1].first) {
    14. dp[i][j]=dp[i-1][j];
    15. }
    16. else {
    17. dp[i][j]=dp[i][j-1];
    18. }
    19. }
    20. }
    21. }
    22. string comm_str=dp[len1][len2].second;
    23. //cout << comm_str;
    24. int i=0, j=0, k=0;
    25. string ret="";
    26. while (k<comm_str.length()) {
    27. char comm_ch=comm_str[k];
    28. while (str1[i] != comm_ch) {
    29. ret += string(1, str1[i]);
    30. i++;
    31. }
    32. while (str2[j] != comm_ch) {
    33. ret += string(1, str2[j]);
    34. j++;
    35. }
    36. ret += string(1, comm_ch);
    37. i++;
    38. j++;
    39. k++;
    40. }
    41. while (i<len1)
    42. ret += string(1, str1[i++]);
    43. while (j<len2)
    44. ret += string(1, str2[j++]);
    45. return ret;
    46. }
    47. };