codice:
public class LCS {

    public int[][] M;
    public String LCS;

    public static int[][] compileM(String a, String b) {
        int[][] L = new int[a.length()+1][b.length()+1];
        for (int i = 0; i < L.length; i++) {
            L[i][0] = 0;
        }
        for (int j=0; j <L[0].length; j++) {
            L[0][j] = 0;
        }
        for (int i = 0; i < a.length(); i++) {
            for (int j=0; j < b.length(); j++) {
                if (a.charAt(i)==b.charAt(j)) {
                    L[i+1][j+1]=L[i][j]+1;
                }
                else {
                    L[i+1][j+1] = Math.max(L[i][j+1], L[i+1][j]);
                }
            }
        }
        return L;
    }

    private String reverse(String s) {
        String temp="";
        for (int i=0; i < s.length(); i++) {
            temp += s.charAt(s.length()-i-1);
        }
        return temp;
    }

    public LCS(String a, String b) {
        LCS = "";
        M = compileM(a,b);
        int i = M.length-1;
        int j = M[0].length-1;
  
        while (i > 0 && j > 0) {
            if (a.charAt(i-1)==b.charAt(j-1)) {
                LCS += a.charAt(i-1);
                i--; j--;
            }
            else {
                if (M[i][j-1] > M[i-1][j]) {
                    j--;
                }
                else {
                    i--;
                }
            }
        }
        LCS = reverse(LCS);
    }

    public String toString() {
        StringBuffer buf = new StringBuffer();
        for (int i=0; i < M.length; i++) {
            for (int j = 0; j < M[0].length; j++) {
                buf.append(M[i][j]+"  ");
            }
            buf.append("\n");
        }
        buf.append("\n\n"+LCS);
        return buf.toString();
    }
    public static void main (String[] args) {
        LCS lcs = new LCS( "ABCBDAB", "BDCABA");
        System.out.println(lcs);
    }
}
Credo sia corretto, o no?