我試圖使用維基百科參考在java中
用Java實現的Wagner-Fischer algorithm
瓦格納菲捨爾算法實現
Java代碼:
public class StringDistance {
public static void main(String[] args) {
int i, j, m, n, temp, tracker;
int[][] d = new int[50][50];
String s = "kitten";
String t = "sitting";
char u[] = s.toCharArray();
char v[] = t.toCharArray();
m = u.length;
n = v.length;
for (i = 0; i <= m; i++) {
d[i][0] = i;
}
for (j = 0; j <= n; j++) {
d[0][j] = j;
}
for (j = 1; j <= m; j++) {
for (i = 1; i <= n; i++) {
if (u[i - 1] == v[j - 1]) {
tracker = 0;
} else {
tracker = 1;
}
temp = Math.min((d[i - 1][j] + 1), (d[i][j - 1] + 1));
d[i][j] = Math.min(temp, (d[i - 1][j - 1] + tracker));
}
}
System.out.println("The levenstien distance" + d[n][m]);
}
}
但上面的代碼爲唯一的工作等長的琴絃。如果我想讓這個工作不平等strings.Please讓我知道如何克服這個問題。
我收到索引越界的錯誤:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at StringDistance.main(StringDistance.java:32)