我想使用Longest Common Subsequence比较两个二进制文件,但是Java堆空间错误让我每隔2048个字节比较一次该文件。 当我想将字节值返回到我的主程序时出现问题,我想一遍又一遍地返回而不删除前一个返回。怎么做递归返回?
我的源代码: public static byte [] Compare(byte [] x,byte [] y){
StringBuffer sb = new StringBuffer();
int i, j;
final int x_length = x.length;
final int y_length = y.length;
int n = 2048;
int m = 2048;
// D[i][j] = direction, L[i][j] = Length of LCS
int[][] D = new int[n + 1][m + 1];
byte[][] L = new byte[n + 1][m + 1]; // { 1, 2, 3 }
// D[i][0] = 0 for 0<=i<=n
// D[0][j] = 0 for 0<=j<=m
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
if (x[i - 1] == y[j - 1]) {
D[i][j] = D[i - 1][j - 1] + 1;
L[i][j] = 1;
} else if (D[i - 1][j] >= D[i][j - 1]) {
D[i][j] = D[i - 1][j];
L[i][j] = 2;
} else {
D[i][j] = D[i][j - 1];
L[i][j] = 3;
}
}
}
// Backtrack
ByteArrayOutputStream lcs = new ByteArrayOutputStream();
i = n;
j = m;
while (i != 0 && j != 0) {
switch (L[i][j]) {
case 1: // diagonal
lcs.write(x[i - 1]); // Unreversed LCS
--i;
--j;
break;
case 2: // up
--i;
break;
case 3: // backward
--j;
break;
}
}
byte[] result = lcs.toByteArray();
// Reverse:
for (i = 0, j = result.length - 1; i < j; ++i, --j) {
byte b = result[i];
result[i] = result[j];
result[j] = b;
}
//return result; << I want to return the initial result
//While not end of file
while(n < x_length && m < y_length){
if(n+2048 < x.length){
n = n+2048;
} else {
n = x.length;
}
if(m+2048 < y.length){
m = m+2048;
} else {
m = y.length;
}
// D[i][j] = direction, L[i][j] = Length of LCS
int[][] D_new = new int[n + 1][m + 1];
byte[][] L_new = new byte[n + 1][m + 1]; // { 1, 2, 3 }
// D[i][0] = 0 for 0<=i<=n
// D[0][j] = 0 for 0<=j<=m
for (i = i+2048; i <= n; i++) {
for (j = j+2048; j <= m; j++) {
if (x[i - 1] == y[j - 1]) {
D_new[i][j] = D_new[i - 1][j - 1] + 1;
L_new[i][j] = 1;
} else if (D_new[i - 1][j] >= D_new[i][j - 1]) {
D_new[i][j] = D_new[i - 1][j];
L_new[i][j] = 2;
} else {
D_new[i][j] = D_new[i][j - 1];
L_new[i][j] = 3;
}
}
}
// Backtrack
ByteArrayOutputStream lcs_next = new ByteArrayOutputStream();
i = n;
j = m;
while (i != 0 && j != 0) {
switch (L[i][j]) {
case 1: // diagonal
lcs_next.write(x[i - 1]); // Unreversed LCS
--i;
--j;
break;
case 2: // up
--i;
break;
case 3: // backward
--j;
break;
}
}
byte[] result_new = lcs_next.toByteArray();
// Reverse:
for (i = 0, j = result_new.length - 1; i < j; ++i, --j) {
byte b = result_new[i];
result_new[i] = result_new[j];
result_new[j] = b;
}
lcs_next.reset();
//return result_new; << appending the result
}
}