最長公共子序列__java實現


關鍵代碼:

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;
}
}
}
}

上述,i=0或j=0時,即X或Y為空序列時,c[i][j]=0。

 

完整代碼:

public class ZCGGZXL {
    /**
     * 最長公共子序列
     *
     * 問題:
     *     給定兩個序列X={x1,x2,...,xn} 和 Y={y1,y2,...,,yn},找出X和Y的最長公共子序列。
     *
     * 測試輸入:
     *     A B C B D A B
     *     B D C A B A
     * 測試輸出:
     *     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 int[x.length+1][y.length+1];
        int[][] c = lcsLength(x,y,b);
        System.out.println(c[x.length][y.length]);
        lcs(x.length,y.length,x,b);
    }

    /**
     * 輸入:x序列,y序列
     * 輸出:b數組,返回數組c。
     * c[i][j]存儲Xi和Yj的最長公共子序列的長度
     * b[i][j]記錄c[i][j]的值是由哪一個子問題的解得到的,在構造最長公共子序列時要用到。
     * @return
     */
    public static int[][] lcsLength(char[] x,char[] y,int[][] b) {
        // 初始化數組c
        int[][] c = new int[x.length+1][y.length+1]; //0存空序列
        for(int i=0;i<c.length;i++){
            for(int j=0;j<c[0].length;j++){
                c[i][j] = 0;
            }
        }
        // 開始規划
        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;
                    }
                }
            }
        }
        return c;
    }

    public static void lcs(int i,int j,char[]x,int[][]b){
        // 結束條件
        if(i==0 || j==0) return;

        // 判斷b[i][j]進入不同分支
        if(b[i][j]==1){
            lcs(i-1,j-1,x,b);
            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);
        }
    }
}
  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM