|
| 1 | +/* |
| 2 | + * |
| 3 | + * Runtime : 12ms, faster than 98.40% |
| 4 | + * Memory : 10.7MB, faster than 85.57% |
| 5 | + * prerequisite : least common subsequence in string |
| 6 | + */ |
| 7 | +class Solution { |
| 8 | +public: |
| 9 | + string shortestCommonSupersequence(string str1, string str2) { |
| 10 | + |
| 11 | + int i = str1.length(); |
| 12 | + int j = str2.length(); |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + int t[i+1][j+1]; |
| 17 | + |
| 18 | + // create matrix of size str1 length as row |
| 19 | + // and str2 length as column |
| 20 | + |
| 21 | + // base condition |
| 22 | + for(int k = 0;k<=i;k++) |
| 23 | + { |
| 24 | + t[k][0] = 0; |
| 25 | + } |
| 26 | + |
| 27 | + // base condition |
| 28 | + for(int k = 0;k<=j;k++) |
| 29 | + { |
| 30 | + t[0][k] = 0; |
| 31 | + } |
| 32 | + |
| 33 | + // to form different solution from all possible length string |
| 34 | + for(int k = 1;k<=i;k++) |
| 35 | + { |
| 36 | + for(int l = 1;l<=j;l++) |
| 37 | + { |
| 38 | + if(str1[k-1] == str2[l-1]) |
| 39 | + { |
| 40 | + t[k][l] = 1+t[k-1][l-1]; |
| 41 | + } |
| 42 | + else{ |
| 43 | + t[k][l] = max(t[k-1][l],t[k][l-1]); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + string res=""; |
| 49 | + |
| 50 | + while(i>0 && j>0) |
| 51 | + { |
| 52 | + // if char are same in str1 and str2, add it one time |
| 53 | + if(str1[i-1]==str2[j-1]) |
| 54 | + { |
| 55 | + res.push_back(str1[i-1]); |
| 56 | + i--;j--; |
| 57 | + } |
| 58 | + else{ |
| 59 | + |
| 60 | + // comparing matrix value to form string |
| 61 | + // add both characters of string to answer |
| 62 | + if(t[i][j-1] > t[i-1][j]) |
| 63 | + { |
| 64 | + res.push_back(str2[j-1]); |
| 65 | + j--; |
| 66 | + } |
| 67 | + else{ |
| 68 | + res.push_back(str1[i-1]); |
| 69 | + i--; |
| 70 | + } |
| 71 | + |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + while(i>0) |
| 76 | + { |
| 77 | + res.push_back(str1[i-1]); |
| 78 | + i--; |
| 79 | + } |
| 80 | + while(j>0) |
| 81 | + { |
| 82 | + res.push_back(str2[j-1]); |
| 83 | + j--; |
| 84 | + } |
| 85 | + reverse(res.begin(),res.end()); |
| 86 | + return res; |
| 87 | + } |
| 88 | +}; |
0 commit comments