Skip to content

Commit e97a2f5

Browse files
authored
Merge pull request #151 from nishagii/feature/longes-common-subsequence-java
PR : DP problem Longest Common Subsequence in Java
2 parents 5a6e06e + 6935193 commit e97a2f5

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class LongestCommonSubsequence {
2+
public static void main(String[] args) {
3+
String str1 = "AGGTAB";
4+
String str2 = "GXTXAYB";
5+
System.out.println("Length of Longest Common Subsequence between \"" + str1 + "\" and \"" + str2 + "\" is: " + lcs(str1, str2));
6+
}
7+
8+
public static int lcs(String str1, String str2) {
9+
int m = str1.length();
10+
int n = str2.length();
11+
int[][] dp = new int[m + 1][n + 1];
12+
13+
for (int i = 0; i <= m; i++) {
14+
for (int j = 0; j <= n; j++) {
15+
if (i == 0 || j == 0) {
16+
dp[i][j] = 0; // Base case: one string is empty
17+
} else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
18+
dp[i][j] = dp[i - 1][j - 1] + 1; // Characters match
19+
} else {
20+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Characters don't match
21+
}
22+
}
23+
}
24+
return dp[m][n];
25+
}
26+
}

0 commit comments

Comments
 (0)