|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +string SCS(string X, string Y, int n, int m) { |
| 5 | + int dp[n + 1][m + 1]; // DP - matrix |
| 6 | + |
| 7 | + // base case of recursion --> for initialization of dp - matrix |
| 8 | + for (int i = 0; i <= n; i++) |
| 9 | + for (int j = 0; j <= m; j++) |
| 10 | + if (i == 0 || j == 0) |
| 11 | + dp[i][j] = 0; |
| 12 | + |
| 13 | + for (int i = 1; i <= n; i++) |
| 14 | + for (int j = 1; j <= m; j++) |
| 15 | + if (X[i - 1] == Y[j - 1]) // when last character is same |
| 16 | + dp[i][j] = 1 + dp[i - 1][j - 1]; |
| 17 | + else // when last character is not same -> pick max |
| 18 | + dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); |
| 19 | + |
| 20 | + int i = n, j = m; |
| 21 | + string scs = ""; |
| 22 | + while (i > 0 && j > 0) { |
| 23 | + if (X[i - 1] == Y[j - 1]) { // when char are eqaul from table obs |
| 24 | + scs += X[i - 1]; // take only once |
| 25 | + i--, j--; // and decrement both |
| 26 | + } |
| 27 | + else if (dp[i][j - 1] > dp[i - 1][j]) { |
| 28 | + scs += Y[j - 1]; // in this we will take the charecter to string |
| 29 | + j--; |
| 30 | + } |
| 31 | + else { |
| 32 | + scs += X[i - 1]; // taking the charecter to string |
| 33 | + i--; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + while (i > 0) { |
| 38 | + scs += X[i - 1]; // take left chareter from str1 |
| 39 | + i--; |
| 40 | + } |
| 41 | + |
| 42 | + while (j > 0) { |
| 43 | + scs += Y[j - 1]; // take left chareter from str1 |
| 44 | + j--; |
| 45 | + } |
| 46 | + |
| 47 | + reverse(scs.begin(), scs.end()); |
| 48 | + |
| 49 | + return scs; |
| 50 | +} |
| 51 | + |
| 52 | +int main() { |
| 53 | + string X, Y; cin >> X >> Y; |
| 54 | + int n = X.length(), m = Y.length(); |
| 55 | + |
| 56 | + cout << SCS(X, Y, n, m) << endl; |
| 57 | + return 0; |
| 58 | +} |
0 commit comments