Key Code:
for(int i=1;i<=x.length;i++){
for(int j=1;j<=y.length;j++){
if(x[i-1]==y[j-1]){
c[i][j] = c[i-1][j-1]+1;
b[i][j] = 1;
}else{
if(c[i-1][j]>=c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = 2;
}else{
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
}
}
}
Above, i = 0 or j = 0, i.e. X or Y is an empty sequence, c [i] [j] = 0.
Complete code:
{class ZCGGZXL public / ** * longest common subsequence * * Question: * Given two sequences X = {x1, x2, ... , xn} and Y = {y1, y2, ... ,, yn }, find the longest common subsequence of X and Y. * * Test input: * ABCBDAB * BDCABA * Test Output: *. 4 * BCBA * / public static void main (String args []) { char [] X = { 'A', 'B', 'C', 'B ',' D ',' A ',' B '}; char [] Y = {' B ',' D ',' C ',' A ',' B ',' A '}; int [] [ ] B = new new int [x.length +. 1] [y.length +. 1]; int [] [] = lcsLength C (X, Y, B); System.out.println (C [x.length] [Y . / ** * Input: x sequence, y sequence * Output: b array, return the array c. * C [i] [j] the length of the longest common subsequence of Xi and Yj stored in the value * b [i] [j] recorded c [i] [j] which is a sub-problem solution obtained in to use when constructing the longest common subsequence. @Return * * / public static int [] [] lcsLength (char [] X, char [] Y, int [] [] B) { // initialize an array C int [] [] = C new new int [x.length +1] [y.length + 1]; // 0 kept empty sequence for (int I = 0; I <c.length; I ++) { for (int J = 0; J <C [0] .length; J ++ ) { C [I] [J] = 0; } } // start planning for (int I =. 1; I <= x.length; I ++) { for (int. 1 = J; J <= y.length; J ++ ) { IF (X [I-. 1] == Y [J-. 1]) { C [I] [J] = C [. 1-I] [J-. 1] + 1'd; if (b [i] [j ] == 1) { B [I] [J] =. 1; } the else { IF (C [I-. 1] [J]> = [I] C [J-. 1]) { C [I] [J] = C [I-. 1 ] [J]; B [I] [J] = 2; } the else { C [I] [J] = C [I] [J-. 1]; B [I] [J] =. 3; } } } } C return; } public static void LCS (I int, int J, char [] X, int [] [] B) { // end condition IF (I == 0 || J == 0) return; // Analyzing b [i] [j] into a different branch LCS (-I. 1,. 1-J, X, B); of System.out.print (X [I-. 1]); }else{ if(b[i][j]==2) lcs(i-1,j,x,b); else lcs(i,j-1,x,b); } } }