|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +int main(){ |
| 5 | + // take input |
| 6 | + string s,t; |
| 7 | + cin>>s>>t; |
| 8 | + |
| 9 | + int sLength = s.length(); |
| 10 | + int tLength = t.length(); |
| 11 | + |
| 12 | + // create dp table |
| 13 | + int dp[sLength][tLength]; |
| 14 | + memset(dp, 0, sizeof dp); |
| 15 | + for(int i=0;i<sLength;i++){ |
| 16 | + for(int j=0;j<tLength;j++){ |
| 17 | + // if the characters are same |
| 18 | + if(s[i] == t[j]) |
| 19 | + dp[i][j] = ((i>0 && j>0) ? dp[i-1][j-1] : 0) + 1; |
| 20 | + // if characters are not same |
| 21 | + // choose the largest common subsequence |
| 22 | + // which could be made with string s[0..i-1] and t[0..j-1] |
| 23 | + else |
| 24 | + dp[i][j] = max(((i>0) ? dp[i-1][j] : 0), ((j>0) ? dp[i][j-1] : 0)); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // now run a backward loop |
| 29 | + // from bottom right corner to the top left corner |
| 30 | + string answer=""; |
| 31 | + int i = sLength-1, j = tLength-1; |
| 32 | + while(i>=0 && j>=0){ |
| 33 | + // you have chosen the common character |
| 34 | + // thus should have come to the current cell from top left diagonal direction |
| 35 | + // so move in opposite direction of that |
| 36 | + if(dp[i][j] == (((i>0 && j>0) ? dp[i-1][j-1] : 0) + 1) && s[i] == t[j]) |
| 37 | + answer+=s[i], i--, j--; |
| 38 | + else if(i>0 && j>0 && dp[i-1][j] > dp[i][j-1]) |
| 39 | + i--; |
| 40 | + else if(i>0 && j>0 && dp[i-1][j] < dp[i][j-1]) |
| 41 | + j--; |
| 42 | + else{ |
| 43 | + if(i>j)i--; |
| 44 | + else j--; |
| 45 | + } |
| 46 | + } |
| 47 | + reverse(answer.begin(), answer.end()); |
| 48 | + cout<<answer; |
| 49 | +} |
0 commit comments