1+ class LongestCommonSubsequence {
2+
3+ public static String getLCS (String str1 , String str2 ) {
4+
5+ //At least one string is null
6+ if (str1 == null || str2 == null )
7+ return null ;
8+
9+ //At least one string is empty
10+ if (str1 .length () == 0 || str2 .length () == 0 )
11+ return "" ;
12+
13+ String [] arr1 = str1 .split ("" );
14+ String [] arr2 = str2 .split ("" );
15+
16+ //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2
17+ int [][] lcsMatrix = new int [arr1 .length + 1 ][arr2 .length + 1 ];
18+
19+ for (int i = 0 ; i < arr1 .length + 1 ; i ++)
20+ lcsMatrix [i ][0 ] = 0 ;
21+ for (int j = 1 ; j < arr2 .length + 1 ; j ++)
22+ lcsMatrix [0 ][j ] = 0 ;
23+ for (int i = 1 ; i < arr1 .length + 1 ; i ++) {
24+ for (int j = 1 ; j < arr2 .length + 1 ; j ++) {
25+ if (arr1 [i -1 ].equals (arr2 [j -1 ])) {
26+ lcsMatrix [i ][j ] = lcsMatrix [i -1 ][j -1 ] + 1 ;
27+ } else {
28+ lcsMatrix [i ][j ] = lcsMatrix [i -1 ][j ] > lcsMatrix [i ][j -1 ] ? lcsMatrix [i -1 ][j ] : lcsMatrix [i ][j -1 ];
29+ }
30+ }
31+ }
32+ return lcsString (str1 , str2 , lcsMatrix );
33+ }
34+
35+ public static String lcsString (String str1 , String str2 , int [][] lcsMatrix ) {
36+ StringBuilder lcs = new StringBuilder ();
37+ int i = str1 .length (),
38+ j = str2 .length ();
39+ while (i > 0 && j > 0 ) {
40+ if (str1 .charAt (i -1 ) == str2 .charAt (j -1 )) {
41+ lcs .append (str1 .charAt (i -1 ));
42+ i --;
43+ j --;
44+ } else if (lcsMatrix [i -1 ][j ] > lcsMatrix [i ][j -1 ]) {
45+ i --;
46+ } else {
47+ j --;
48+ }
49+ }
50+ return lcs .reverse ().toString ();
51+ }
52+
53+ public static void main (String [] args ) {
54+ String str1 = "DSGSHSRGSRHTRD" ;
55+ String str2 = "DATRGAGTSHS" ;
56+ String lcs = getLCS (str1 , str2 );
57+
58+ //Print LCS
59+ if (lcs != null ) {
60+ System .out .println ("String 1: " + str1 );
61+ System .out .println ("String 2: " + str2 );
62+ System .out .println ("LCS: " + lcs );
63+ System .out .println ("LCS length: " + lcs .length ());
64+ }
65+ }
66+ }
0 commit comments