import java.util.*; public class Hirschberg { static int K[][]; /* ================================================================== findLCS(m, n, A, B): find the LCS in A[0..(m-1)] and B[0..(n-1)] ================================================================== */ public static String findLCS(int m, int n, String A, String B) { int i, j; String C = ""; if ( A.length() != m || B.length() != n ) { System.out.println("Problem !"); } if ( n == 0 ) return ""; if ( m == 1 ) { /* ===================================== The input A consists of 1 character Find the single common character in B ===================================== */ for ( i = 0; i < n; i++ ) if ( B.charAt(i) == A.charAt(0) ) return( A ); return ""; // Not found.... } /* ===================================================== General case: A[0..(m-1)] has 2 or more characters ===================================================== */ i = m/2 ; int x1=0, x2=0; int z = solveLCS( A, B ) ; /* System.out.println("LCS( " + A + "," + B + ") = " + z ); */ for ( j = 0; j < n; j++ ) { x1 = solveLCS( A.substring(0, i), B.substring(0, j) ) ; x2 = solveLCS( A.substring(i, m), B.substring(j, n) ) ; /* System.out.println("Trying: "); System.out.println(" " + A.substring(0, i) + "<->" + B.substring(0, j) + " ==> " + x1); System.out.println(" " + A.substring(i, m) + "<->" + B.substring(j, n) + " ==> " + x2); */ if ( x1 + x2 == z ) break; } if ( x1 + x2 != z ) { System.out.println("x1 + x2 == z NOT FOUND !"); } String C1 = findLCS(i, j, A.substring(0,i), B.substring(0,j) ); String C2 = findLCS(m-i, n-j, A.substring(i,m), B.substring(j,n) ); System.out.println("C1 = " + C1 + ", C2 = " + C2); return ( C1 + C2 ); } public static int solveLCS(String x, String y) { int i, j; if ( x.length() == 0 || y.length() == 0 ) return 0; for (j = 0; j < y.length()+1; j++) K[1][j] = 0; // x = "" ===> LCS = 0 for (i = 1; i < x.length()+1; i++) { /* ===================================================== Recycle phase: copy row K[1][...] to row K[0][...] ===================================================== */ for ( j = 0; j < y.length()+1; j++) K[0][j] = K[1][j]; K[1][0] = 0; // y = "" ===> LCS = 0 for (j = 1; j < y.length()+1; j++) { if ( x.charAt(i-1) == y.charAt(j-1) ) { K[1][j] = K[0][j-1] + 1; } else { K[1][j] = Math.max( K[0][j], K[1][j-1] ); } } } return K[1][y.length()]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String x; String y; String z; int i, j, r; System.out.print("x = "); x = in.next(); System.out.print("y = "); y = in.next(); K = new int[2][y.length()+1]; // Linear space !!! z = findLCS(x.length(), y.length(), x, y); System.out.println("LCS = " + z); } }