以下是一个基于动态规划的编辑距离算法的java实现:

public class EditDistance {
    
    public static int calculate(String str1, String str2) {
        int[][] dp = new int[str1.length() + 1][str2.length() + 1];
        
        for (int i = 0; i <= str1.length(); i++) {
            dp[i][0] = i;
        }
        
        for (int j = 0; j <= str2.length(); j++) {
            dp[0][j] = j;
        }
        
        for (int i = 1; i <= str1.length(); i++) {
            for (int j = 1; j <= str2.length(); j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }
        
        return dp[str1.length()][str2.length()];
    }

    public static void main(String[] args) {
        String str1 = "kitten";
        String str2 = "sitting";
        int distance = calculate(str1, str2);
        System.out.println("The edit distance between " + str1 + " and " + str2 + " is " + distance);
    }
}

在这个实现中,我们使用一个二维数组来存储所有可能的编辑距离。我们首先初始化数组的第一行和第一列,然后使用两个嵌套的循环来填充数组的其余部分。在每个单元格中,我们检查当前字符是否相同。如果是,则我们可以将当前单元格的值设置为左上角单元格的值,因为我们不需要进行任何编辑操作。否则,我们将当前单元格的值设置为左上角、左边和上边单元格的最小值加1,因为我们需要进行一次编辑操作来将字符串匹配。最后,我们返回数组的右下角单元格,它包含最终的编辑距离

提供一个编辑距离算法的java实现

原文地址: http://www.cveoy.top/t/topic/dHNl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录