Skip to content

Commit 807f2b5

Browse files
committed
add: LongestCommonSubsequence
1 parent e2a125b commit 807f2b5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class LongestCommonSubsequence {
2+
public int longestCommonSubsequence(String s1, String s2) {
3+
// Base case: Set the last row and last column to 0 by
4+
// initializing the entire DP table with 0s.
5+
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
6+
// Populate the DP table.
7+
for (int i = s1.length() - 1; i >= 0; i--) {
8+
for (int j = s2.length() - 1; j >= 0; j--) {
9+
// If the characters match, the length of the LCS at
10+
// 'dp[i][j]' is 1 + the LCS length of the remaining
11+
// substrings.
12+
if (s1.charAt(i) == s2.charAt(j)) {
13+
dp[i][j] = 1 + dp[i + 1][j + 1];
14+
}
15+
// If the characters don't match, the LCS length at
16+
// 'dp[i][j]' can be found by either:
17+
// 1. Excluding the current character of s1.
18+
// 2. Excluding the current character of s2.
19+
else {
20+
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
21+
}
22+
}
23+
}
24+
return dp[0][0];
25+
}
26+
}

0 commit comments

Comments
 (0)