Advertisement
nikunjsoni

1092

Jun 16th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string shortestCommonSupersequence(string& A, string& B) {
  4.         int i = 0, j = 0;
  5.         string res = "";
  6.         for(char c : lcs(A, B)) {
  7.             while(A[i] != c)
  8.                 res += A[i++];
  9.             while(B[j] != c)
  10.                 res += B[j++];
  11.             res += c, i++, j++;
  12.         }
  13.         return res + A.substr(i) + B.substr(j);
  14.     }
  15.  
  16.     string lcs(string& A, string& B) {
  17.         int n = A.size(), m = B.size();
  18.         vector<vector<string>> dp(n + 1, vector<string>(m + 1, ""));
  19.         for (int i = 0; i < n; ++i)
  20.             for (int j = 0; j < m; ++j)
  21.                 if (A[i] == B[j])
  22.                     dp[i + 1][j + 1] = dp[i][j] + A[i];
  23.                 else
  24.                     dp[i + 1][j + 1] = dp[i + 1][j].size() > dp[i][j + 1].size() ?  dp[i + 1][j] : dp[i][j + 1];
  25.         return dp[n][m];
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement