[LintCode/LeetCode] Edit Distance

505 查看

Problem

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:

Insert a character
Delete a character
Replace a character

Example

Given word1 = "mart" and word2 = "karma", return 3.

Note

构造dp[i][j]数组,iword1index+1jword2index+1dp[i][j]是将i位的word1转换成j位的word2需要的步数。初始化dp[i][0]dp[0][i]dp[0][0]到它们各自的距离i,然后两次循环ij即可。
理解三种操作:insertion是完成i-->j-1之后,再插入一位才完成i-->jdeletion是完成i-->j之后,发现i多了一位,所以i-1-->j才是所求,需要再删除一位才完成i-->j;而replacement则是换掉word1的最后一位,即之前的i-1-->j-1已经完成,如果word1的第i-1位和word2的第j-1位相等,则不需要替换操作,否则要替换一次完成i-->j

Solution

public class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m+1][n+1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0) dp[i][j] = j;
                else if (j == 0) dp[i][j] = i;
                else {
                    int insert = dp[i][j-1] + 1;
                    int delete = dp[i-1][j] + 1;
                    int replace = dp[i-1][j-1] + (word1.charAt(i-1) == word2.charAt(j-1) ? 0 : 1);
                    dp[i][j] = Math.min(insert, Math.min(delete, replace));
                }
            }
        }
        return dp[m][n];
    }
}