Edit Distance(编辑距离)

http://www.lintcode.com/en/problem/edit-distance/

public class Solution {
    /*
     * @param word1: A string
     * @param word2: A string
     * @return: The minimum number of steps.
     */
    public int minDistance(String word1, String word2) {
        // write your code here
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];
//        dp表示当前位置最小的编辑数
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = i;
        }
        for (int i = 0; i < dp[0].length; i++) {
            dp[0][i] = i;
        }
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
//                    删除
                    int delete = dp[i - 1][j] + 1;
//                    添加
                    int add = dp[i][j - 1] + 1;
//                    修改
                    int edit = dp[i - 1][j - 1]+1;
                    dp[i][j] = Math.min(delete, Math.min(add, edit));
                }
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }
}

你可能感兴趣的:(Edit Distance(编辑距离))