1

Edit Distance

典型的动态规划题目。维护一个二维数组dis[][]dis[i][j]表示:word1的前i个元素与word2的前j个元素的edit distance值。递推关系为:

  • word1[i] == word2[j]dis[i][j] = dis[i][j - 1]
  • word[i] != word2[j]dis[i][j] = min(dis[i - 1][j - 1], dis[i] [j - 1], dis[i - 1][j]) + 1

解释一下第二种情况下的递推公式:

  • dis[i][j] = dis[i - 1][j - 1] + 1意味着替换字符
  • dis[i][j] = dis[i - 1][j] + 1意味着删除字符
  • dis[i][j] = dis[i][j - 1] + 1意味着插入字符

实现代码:

javapublic class Solution {
    public int minDistance(String word1, String word2) {
        int[] result = new int[word1.length() + 1];
        for (int i = 0; i < result.length; i++)
            result[i] = i;
        for (int i = 0; i < word2.length(); i++) {
            int[] newResult = new int[result.length];
            newResult[0] = i + 1;
            for (int j = 0; j < word1.length(); j++) {
                if (word1.charAt(j) == word2.charAt(i)) {
                    newResult[j + 1] = result[j];
                } else {
                    newResult[j + 1]  = Math.min(result[j], Math.min(result[j + 1], newResult[j])) + 1;
                }
            }
            result = newResult;
        }
        return result[result.length - 1];
    }
}

findingea
1.1k 声望64 粉丝