1
+
2
+ /*
3
+ Given two strings X and Y of lengths m and n respectively, find the length of the smallest string which has both, X and Y as its sub-sequences.
4
+ Note: X and Y can have both uppercase and lowercase letters.
5
+
6
+ Example 1
7
+
8
+ Input:
9
+ X = abcd, Y = xycd
10
+ Output: 6
11
+ Explanation: Shortest Common Supersequence
12
+ would be abxycd which is of length 6 and
13
+ has both the strings as its subsequences.
14
+ Example 2
15
+
16
+ Input:
17
+ X = efgh, Y = jghi
18
+ Output: 6
19
+ Explanation: Shortest Common Supersequence
20
+ would be ejfghi which is of length 6 and
21
+ has both the strings as its subsequences.
22
+ */
23
+
24
+
25
+ #include < bits/stdc++.h>
26
+ using namespace std ;
27
+
28
+
29
+ class Solution
30
+ {
31
+ public:
32
+
33
+ int LCS (string X, string Y, int m, int n){
34
+ int dp[m+1 ][n+1 ];
35
+ memset (dp,-1 ,sizeof (dp));
36
+ for (int i=0 ;i<m+1 ;i++)
37
+ {
38
+ for (int j=0 ;j<n+1 ;j++)
39
+ {
40
+ if (i==0 || j==0 ) dp[i][j]=0 ;
41
+ else if (X[i-1 ] == Y[j-1 ]){
42
+ dp[i][j] = 1 +dp[i-1 ][j-1 ];
43
+ }
44
+ else {
45
+ dp[i][j] = max (dp[i-1 ][j] , dp[i][j-1 ]);
46
+ }
47
+ }
48
+ }
49
+ return dp[m][n];
50
+ }
51
+ int shortestCommonSupersequence (string X, string Y, int m, int n)
52
+ {
53
+ // code here
54
+
55
+
56
+ return (m + n) - LCS (X, Y , m , n);
57
+ }
58
+ };
59
+
60
+
61
+
62
+ int main ()
63
+ {
64
+
65
+ int t;
66
+
67
+ // taking total testcases
68
+ cin >> t;
69
+ while (t--){
70
+ string X, Y;
71
+ // taking String X and Y
72
+ cin >> X >> Y;
73
+
74
+ // calling function shortestCommonSupersequence()
75
+ Solution obj;
76
+ cout << obj.shortestCommonSupersequence (X, Y, X.size (), Y.size ())<< endl;
77
+ }
78
+ return 0 ;
79
+ }
80
+
0 commit comments