8000 added Longest common subsequence problem to Dynamic Programming · RockLee444/Java-Algorithms@3cfa375 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3cfa375

Browse files
committed
added Longest common subsequence problem to Dynamic Programming
1 parent 280509f commit 3cfa375

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.*;
2+
3+
public class LongestCommonSubSequence {
4+
static int countlcs(String s1, String s2) {
5+
int[][] count = new int[s1.length() + 1][s2.length() + 1];
6+
for (int i = s1.length(); i >= 0; i--) {
7+
for (int j = s2.length(); j >= 0; j--) {
8+
if (i == s1.length()) {
9+
count[i][j] = 0;
10+
} else if (j == s2.length()) {
11+
count[i][j] = 0;
12+
} else if (i == s1.length() && j == s2.length()) {
13+
count[i][j] = 0;
14+
} else {
15+
count[i][j] = s1.charAt(i) == s2.charAt(j) ? count[i + 1][j + 1] + 1
16+
: Math.max(count[i + 1][j], count[i][j + 1]);
17+
}
18+
}
19+
}
20+
return count[0][0];
21+
}
22+
23+
public static void main(String[] args) {
24+
String s1 = "abcdabr";
25+
String s2 = "aebdabr";
26+
System.out.println(countlcs(s1, s2));
27+
28+
}
29+
}

0 commit comments

Comments
 (0)
0