I'm learning about the longest common subsequence, Using these algorithm:
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=1;i<m+1;i++){
for(int j=1;j<n+1;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 ErrorCharAt(Unknow Source) and didn't do anything.
i'm trying to change
for(int i=1;i<m+1;i++){
for(int j=1;j<n+1;j++){
to
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
the result is this line IndexOutofBoud
if (S[row][col] == D){
....
}
Also,if i change int i and j to 0 then E below would be index -1 and error
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][i-1]+1;
......
}
i'm so lost right now.Can anyone help me?