File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments