Java中的Levenshtein算法

问题描述

受此Wikipedia article的启发,我正在尝试用Java实现Levenshtein的算法。

public static int indicator(char a,char b) {
    return (a == b) ? 0 : 1;
}

public static int levenshtein(String token1,String token2) {
    int[] levi = new int[token2.length() + 1];
    int[] levi_1 = new int[token2.length() + 1];

    // initialize column i=0
    for (int j = 0; j <= token2.length(); j++)
        levi_1[j] = j;

    // columns i=1 -> i=len(token1)
    for (int i = 1; i <= token1.length(); i++) {
        // lev_a,b(i,0) = i
        levi[0] = i;
        // update rest of column i
        for (int j = 1; j <= token2.length(); j++) {
            levi[j] = Math.min(Math.min(levi_1[j] + 1,levi[j - 1] + 1),levi_1[j - 1] + indicator(token1.charat(i - 1),token2.charat(j - 1)));
        }

        // save column i to update column i+1
        levi_1 = levi;
    }

    return levi[token2.length()];
}

但是在字符串“ Maus”和“ Haus”上测试此错误答案为4。您能帮我解决我做错的事情吗?

解决方法

问题来自此行:

levi_1 = levi;

此行不会更改levi_1数组中的每个值,而只会更改其引用;调用levi_1[0]levi_1[1]等时,值仍然相同。

我建议您改写这些行:

for (int k = 0; k < levi.length; k++)
    levi_1[k] = levi[k];