最长公共子序列问题(LCS) Longest common subsequence

问题描述:序列X={x1,x2,…,xn},Y={y1,y2,…,yn},当Z={z1,z2…,zn}是X的严格递增下标顺序(可以不连续)的子集,也是Y的严格递增下标顺序(可以不连续)的子集,则Z是X和Y的公共子序列。例如X={A,B,C,B,D,A,B},Y={B,D,C,A,B,A},{B,C,A}、{B,C,B,A}、{B,D,A,B}都是X和Y的公共子序列。其中最长的公共子序列叫做Longest common subsequence,即经典的LCS。

具体点:char[]xArray和char[] yArray是字符数组,长度分别为m、n,求他们的LCS

package dynamic_programming;
//《算法分析》  p111
public class LongestPublicSubSequenceProblem {
    public static char[] longestPublicSubSequence(char[] X,char[] Y){
        int lenx = X.length; int leny = Y.length;
        int[][] l = new int[lenx+1][leny+1]; 
        int[][] s = new int[lenx+1][leny+1];

        for (int j = 1; j <= leny; j++) {
            for (int i = 1; i <= lenx; i++) {
                if(X[i-1]==Y[j-1]){ //相当于
                    l[i][j] = l[i-1][j-1]+1;
                    s[i][j] = 1;
                }else if(l[i][j-1]>l[i-1][j]){
                    l[i][j] = l[i][j-1];
                    s[i][j] = 3;
                }else{
                    l[i][j] = l[i-1][j];
                    s[i][j] = 2;
                }
            }
        }
        int num = l[lenx][leny];
        char[] re = new char[num];
        int i = lenx,j = leny;
        while(i>0&&j>0){
            if(s[i][j]==1){
                re[num-1] = X[i-1];
                num--;
                i--;
                j--;
            }else if(s[i][j]==2){
                i--;
            }else{
                j--;
            }
        }

        print(l);
        System.out.println("=============================");
        print(s);

        return re;
    }

    public static void print(int[][] arr){
        for (int i = 0; i < arr[0].length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[j][i]+"  ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        char[] X = new char[]{'a','b','c','b','d','b'};
        char[] Y = new char[]{'a','c','b','b','a','b','d','b','b'};
        char[] result = longestPublicSubSequence(Y,X);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }

}

运行结果:
最长公共子序列问题(LCS) Longest common subsequence_第1张图片

你可能感兴趣的:(算法和数据结构,经典算法问题)