public class LCS { static String ans; public static int solveLCS(int i, int j, String x, String y, String s) { int sol1, sol2; if (i == 0 || j == 0) { if ( s.length() > ans.length() ) ans = s; return(0); } if ( x.charAt(i-1) == y.charAt(j-1) ) { sol1 = solveLCS(i-1, j-1, x, y, x.charAt(i-1) + s); return(sol1 + 1); } else { sol1 = solveLCS(i-1, j, x, y, s); sol2 = solveLCS(i, j-1, x, y, s); return( (sol1 >= sol2) ? sol1 : sol2 ); } } public static void main(String[] args) { String x = "abcabcabc"; String y = "babacbab"; int r; ans = ""; r = solveLCS(x.length(), y.length(), x, y, ""); System.out.println("Max length = " + r); System.out.println("LCS = " + ans); } }