最常见的子序列,数组索引超出范围

时间:2016-05-12 17:31:53

标签: java arrays string dynamic-programming indexoutofboundsexception

我正在学习最长的常见子序列,使用这些算法:

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

但该程序返回IndexOutofBound Exception并且没有做任何事情。

任何人都可以帮助我吗?

为什么会发生这种情况,我该如何解决?

0 个答案:

没有答案