/** * @author BiangHoo * * 2013年9月11日 */ public class LCS { public static void main(String[] args) { String X[] = {"A","B","C","B","D","A","B"}; String Y[] = {"B","D","C","A","B","A"}; LCS_Length(X,Y); } static void display(String array[][]){ for(int i=0;i<array.length;i++){ for(int j=0;j<array[0].length;j++){ System.out.print(array[i][j]+" "); } System.out.print("\n"); } System.out.print("\n"+"the LCS is: "); } static void LCS_Length(String X[],String Y[]){ int xlen = X.length; int ylen = Y.length; String b[][] = new String[xlen+1][ylen+1]; int c[][] = new int[xlen+1][ylen+1]; for(int i=0;i<xlen+1;i++){ c[i][0] = 0; } for(int i=0;i<ylen+1;i++){ c[0][i] = 0; } for(int i=1;i<xlen+1;i++){//bottom to top for(int j=1;j<ylen+1;j++){ if(X[i-1]==Y[j-1]){ c[i][j] = c[i-1][j-1]+1; b[i][j] ="arrow"; }else if(c[i-1][j] >= c[i][j-1]){ c[i][j] = c[i-1][j]; b[i][j] = "up"; }else{ c[i][j] = c[i][j-1]; b[i][j] = "left"; } } } display(b); Print_LCS(b,X,xlen,ylen); } static void Print_LCS(String [][] b,String[]X,int i,int j){ if(b[i][j] == null){ return ; } if(b[i][j] == "arrow"){ Print_LCS(b,X,i-1,j-1); System.out.print(X[i-1]+" "); }else if(b[i][j] == "up"){ Print_LCS(b,X,i-1,j); }else{ Print_LCS(b,X,i,j-1); } } }