72. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

这道题看的答案,据说是经典DP问题,下面这个视频有非常详尽的解法:
Minimum Edit Distance Dynamic Programming

但并没有很具体地解释为什么这样做可以。

简单来讲就是画个矩阵int[][] matrix,上面是word1, 左边是word2, 然后填出从对应的word1到word2需要走的最小路径。


72. Edit Distance_第1张图片

要注意,在matrix[i][j]的地方,对应的是word1.charAt(j - 1)和word2.charAt(i - 1),因为为了方便状态函数的初始化,我们有一个f[0][0] = 0是空对空。

submit 1:

72. Edit Distance_第2张图片
![Uploading Screen Shot 2017-10-06 at 1.58.45 PM_745636.png . . .]

AC:

72. Edit Distance_第3张图片
Screen Shot 2017-10-06 at 1.58.45 PM.png
class Solution {
    public int minDistance(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        //state:f[x][y] means in the matrix i draw, how many steps needed to transfer word1 to word2
        int[][] f = new int[m + 1][n + 1];
        
        //initialize
        for (int i = 0; i < n + 1; i++){
            f[0][i] = i;
        }
        for (int i = 0; i < m + 1; i++){
            f[i][0] = i;
        }
        
        //function
        for (int i = 1; i < m + 1; i++){
            for (int j = 1; j < n + 1; j++){
                if (word1.charAt(j - 1) != word2.charAt(i - 1)){
                    f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i][j - 1], f[i - 1][j])) + 1;
                } else {
                    f[i][j] = f[i - 1][j - 1];
                }
            }
        }
        return f[m][n];
    }
}

你可能感兴趣的:(72. Edit Distance)