/* --------------------------------- LCS using reverse direction Seems to work --------------------------------- */ import java.util.*; public class LCS_rev { static String ans; public static int solveLCS(int i, int j, String x, String y, String s) { int sol1, sol2; if (i == x.length() || j == y.length()) { if ( s.length() > ans.length() ) ans = s; return(0); } /* */ System.out.println(); System.out.println("i = " + i); System.out.println("x.length()-1 = " + (x.length()-1)); System.out.println("j = " + j); System.out.println("y.length()-1 = " + (y.length()-1)); if ( x.charAt(i) == y.charAt(j) ) { sol1 = solveLCS(i+1, j+1, x, y, s + x.charAt(i)); 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) { 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(); ans = ""; r = solveLCS(0, 0, x, y, ""); System.out.println("Max length = " + r); System.out.println("LCS = " + ans); } }