我坐在这里,为我的 Java 主程序编程一些算法(到目前为止是第一个)。我对 levenshtein 算法进行了很好的编程,这要归功于 wiki 对新手的伪代码非常好,还有一个很好的教程:D
然后我决定升级到 Damerau 并添加了额外的行,但后来我读到它不是 DL 算法,而是 OptimalStringAlignmentDistance。我尝试阅读 actionscript 代码以了解我需要添加哪些内容才能将其添加到 DL 中,但却感到困惑。我去过不同的地方,代码看起来像 Java,但它们也都使用了错误的伪代码。
花了半天时间我放弃了,决定在这里问。有没有人可以帮助我将此代码升级到 Java 中的 Damerau-Levenshtein?
public class LevensteinDistance {
private static int Minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
private static int Minimum (int a, int b) {
return Math.min(a, b);
}
public static int computeLevensteinDistance(String s, String t){
int d[][];
int n; // length of s
int m; // length of t
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
n = s.length ();
m = t.length ();
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
d = new int[n+1][m+1];
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
for(i = 1; i <= n; i++) {
s_i = s.charAt (i - 1);
for(j = 1; j <= m; j++) {
t_j = t.charAt (j - 1);
if(s_i == t_j){
cost = 0;
}else{
cost = 1;
}
d[i][j] = Minimum(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
if(i > 1 && j > 1 && s_i == t_j-1 && s_i-1 == t_j){
d[i][j] = Minimum(d[i][j], d[i-2][j-2] + cost);
}
}
}
return d[n][m];
}
// public static void main(String[] args0){
// String a = "I decided it was best to ask the forum if I was doing it right";
// String b = "I thought I should ask the forum if I was doing it right";
// System.out.println(computeLevensteinDistance(a, b));
// }
}