0

I'm learning about the longest common subsequence, Using these algorithm:

cost table algorthm


enter image description here

While, the Input is 
X = SCHOOL
Y = SPOOL
if i'm correct the answer should be  "LOOS"
so i decided to write a JAVA Program to help me with the answers,
using code below

    public class LCS {

    static int[][] E;
    static int[][] S;
    static int D;
    static int T;
    static int L;
    public static void LCS_cost(String X,String Y)
    {       
        int m = X.length();
        int n = Y.length();
        E = new int[m][n];
        S = new int[m][n];
        for(int i=0;i<m;i++){
            E[i][0] = 0;
        }
        for(int j=0;j<n;j++){
            E[0][j] = 0;
        }
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(X.charAt(i) == Y.charAt(j)){
                    E[i][j] = E[i-1][j-1]+1;
                    D =  E[i-1][j-1]+1;
                    S[i][j] = D;//Diagonal Direction    
                }
                else if (E[i-1][j]>=E[i][j-1]){
                        E[i][j] = E[i-1][j];
                        T = E[i-1][j];
                        S[i][j] = T;//TOP
                }
                else
                        E[i][j] = E[i][j-1];
                        L = E[i][j-1];
                        S[i][j] = L;//Left
            }
        }

    }

    public static void Backtrack(int[][] S,String X,String Y){
    int row = X.length();
    int col = Y.length();   

    while (row > 0 || col > 0){
        if (S[row][col] == D){
            System.out.print(X.charAt(row));
            row--;
            col--;
        }
        else if (S[row][col] == T){
            row--;
        }
        else
            col--;
    }
    }
    public static void main(String[] args) {
        new  LCS();
        LCS_cost("SCHOOL","SPOOL");
        Backtrack(S,"SCHOOL", "SPOOL");
    }
}

But the program return an IndexOutofBound Exception and didn't do anything.

Can anyone help me?

Why this happen and how can I fix it?

0 Answers0