import java.util.*; public class LCS2 { static int L[][]; static int max; static String ans; public static int solveLCS(int i, int j, String x, String y, int n, String s) { int sol1, sol2; if (i == 0 || j == 0) { /* -------------------- We have an answer -------------------- */ if ( n >= max ) { max = n; ans = s; // Remember the best answer } return(0); } if ( L[i][j] > 0 ) { return( L[i][j] ); } if ( x.charAt(i-1) == y.charAt(j-1) ) { sol1 = solveLCS(i-1, j-1, x, y, n+1, x.charAt(i-1) + s); L[i][j] = sol1 + 1; return( L[i][j] ); } else { sol1 = solveLCS(i-1, j, x, y, n, s); sol2 = solveLCS(i, j-1, x, y, n, s); L[i][j] = (sol1 >= sol2) ? sol1 : sol2; return( L[i][j] ); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String x; String y; int r; System.out.print("x = "); x = in.next(); System.out.print("y = "); y = in.next(); L = new int[x.length()+1][y.length()+1]; ans = ""; r = solveLCS(x.length(), y.length(), x, y, 0, ""); System.out.println("Max length = " + r); System.out.println("LCS = " + ans); } }