Skip to content

Commit 2e166fd

Browse files
committed
Add LongestCommonSubsequence
1 parent fec8ead commit 2e166fd

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.packt.datastructuresandalg.lesson4.lcs;
2+
3+
public class LongestCommonSubsequence {
4+
public int length(String x, String y) {
5+
int m = x.length();
6+
int n = y.length();
7+
int[][] c = new int[m + 1][n + 1];
8+
for (int i = 1; i <= m; i++) {
9+
for (int j = 1; j <= n; j++) {
10+
if (x.charAt(i - 1) == y.charAt(j - 1))
11+
c[i][j] = c[i - 1][j - 1] + 1;
12+
else
13+
c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]);
14+
}
15+
}
16+
return c[m][n];
17+
}
18+
19+
public static void main(String[] args) {
20+
String s1 = "ACCGGTCGAGTGCGCGGAAGCCGGCCGAA";
21+
String s2 = "GTCGTTCGGAATGCCGTTGCTCTGTAAA";
22+
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
23+
System.out.println("Length of longest common subsequence = " + lcs.length(s1, s2));
24+
}
25+
}

0 commit comments

Comments
 (0)