Skip to content

Commit 5a96274

Browse files
authored
Add Shortest Common Supersequence Length (TheAlgorithms#2516)
1 parent 3b35cc1 commit 5a96274

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Java program to find length of the shortest supersequence
2+
class ShortestSuperSequence {
3+
4+
// Function to find length of the
5+
// shortest supersequence of X and Y.
6+
static int shortestSuperSequence(String X, String Y)
7+
{
8+
int m = X.length();
9+
int n = Y.length();
10+
11+
// find lcs
12+
int l = lcs(X, Y, m, n);
13+
14+
// Result is sum of input string
15+
// lengths - length of lcs
16+
return (m + n - l);
17+
}
18+
19+
// Returns length of LCS
20+
// for X[0..m - 1], Y[0..n - 1]
21+
static int lcs(String X, String Y, int m, int n)
22+
{
23+
int[][] L = new int[m + 1][n + 1];
24+
int i, j;
25+
26+
// Following steps build L[m + 1][n + 1]
27+
// in bottom up fashion. Note that
28+
// L[i][j] contains length of LCS
29+
// of X[0..i - 1]and Y[0..j - 1]
30+
for (i = 0; i <= m; i++) {
31+
for (j = 0; j <= n; j++) {
32+
if (i == 0 || j == 0)
33+
L[i][j] = 0;
34+
35+
else if (X.charAt(i - 1) == Y.charAt(j - 1))
36+
L[i][j] = L[i - 1][j - 1] + 1;
37+
38+
else
39+
L[i][j] = Math.max(L[i - 1][j],
40+
L[i][j - 1]);
41+
}
42+
}
43+
44+
// L[m][n] contains length of LCS
45+
// for X[0..n - 1] and Y[0..m - 1]
46+
return L[m][n];
47+
}
48+
49+
// Driver code
50+
public static void main(String args[])
51+
{
52+
String X = "AGGTAB";
53+
String Y = "GXTXAYB";
54+
55+
System.out.println("Length of the shortest "
56+
+ "supersequence is "
57+
+ shortestSuperSequence(X, Y));
58+
}
59+
}

0 commit comments

Comments
 (0)