交换单词

时间:2017-07-31 17:05:23

标签: java levenshtein-distance

我面临一些levenshtein矩阵的问题我已经实施了。我是一个完整的新手,所以这个问题对某些人来说可能看起来很愚蠢,但是我一直在盯着我们这个问题而且无法弄清楚,为什么它没有成功。 以下是我在主要课程中测试的单词:

public static void main(String[] args) {
        // just some random words to picture my problem
        LevenshteinLogic levenshteinLogic = new LevenshteinLogic();
        int levenshteinZahl = levenshteinLogic.getLevenshteinDifference("abcdefghij", "adb");
        System.out.println(levenshteinZahl);
        levenshteinZahl = levenshteinLogic.getLevenshteinDifference("adb", "abcdefghij");
        System.out.println(levenshteinZahl);
    }

得到的矩阵(加上最后的levenshtein差异)看起来像这样:

0 1 2
1 0 0
2 1 1
3 2 2
4 3 2
5 4 3
6 5 4
7 6 5
8 7 6
9 8 7
8

0 1 2 3 4 5 6 7 8 9
1 0 0 0 0 0 0 0 0 0
2 1 1 1 0 1 1 1 1 1
2

这是我写的levenshtein课程:

任何人都可以看到错误吗?是不是应该做同样的事情,不管哪个词比另一个更长?

public class LevenshteinLogic {
    public int getLevenshteinDifference(String word1, String word2) {
        int levenshteinMatrix[][] = new int[word1.length() + 1][word2.length() + 1];
        final int word1Length = word1.length();
        final int word2Length = word2.length();
        // make sure capital letters aren't a problem
        word1 = word1.toLowerCase();
        word2 = word2.toLowerCase();
        // if empty, return length of other word
        if (word1Length == 0) return word2Length;
        if (word2Length == 0) return word1Length;

        // fill levenshteinMatrix first lines (x and y)
        for (int i = 0; i < (word1Length + 1); i++) {
            levenshteinMatrix[i][0] = i;
        }
        for (int i = 0; i < (word2Length + 1); i++) {
            levenshteinMatrix[0][i] = i;
        }

        for (int x = 1; x < (word1Length + 1); x++) {
            for (int y = 1; y < (word2Length + 1); y++) {
                int notMatching = 0;
                if (word1.charAt(x - 1) != word2.charAt(y - 1)) {
                    notMatching = 1;
                }
                int minValue = levenshteinMatrix[x - 1][y] + 1;
                if ((levenshteinMatrix[x][y - 1] + 1) < minValue) {
                    minValue = levenshteinMatrix[x][y - 1];
                }
                if ((levenshteinMatrix[x - 1][y - 1] + notMatching) < minValue) {
                    minValue = levenshteinMatrix[x - 1][y - 1] + notMatching;
                }
                levenshteinMatrix[x][y] = minValue;
                System.out.print(levenshteinMatrix[x-1][y-1] + " ");
            }
            System.out.println(" ");
        }
        return levenshteinMatrix[word1Length][word2Length];
    }
}

我知道我可以通过检查单词的长度并给出正确的顺序来解决这个问题,但我真的希望了解那里发生了什么。毕竟,我刚刚开始学习这一切。 所有帮助都非常感谢! =)

0 个答案:

没有答案