Edit Distance 解答

Question

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

For example, given word1 = "mart" and word2 = "karma", return 3.

Solution

DP 四要素:1. State 2. Function 3. Initialization 4. Answer

令dp[i][j]表示长度为i的word1和长度为j的word2的最小距离。假设末位分别为x和y。那么根据x和y是否相同,考虑情况如下:

1. x == y

dp[i][j] = dp[i-1][j-1]

2. x != y

a) Delete x => dp[i-1][j] + 1

b) Insert y => dp[i][j-1] + 1

c) Replace x with y => dp[i-1][j-1] + 1

dp[i][j]取a,b,c中最小值。

public class Solution {
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    public int minDistance(String word1, String word2) {
        // write your code here
        int len1 = word1.length();
        int len2 = word2.length();
        // dp[i][j] represents min distance for word1[0, i - 1] and word2[0, j - 1]
        int[][] dp = new int[len1 + 1][len2 + 1];
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    // delete word1[i - 1]
                    int x = dp[i - 1][j] + 1;
                    // insert word2[j - 1] into word1
                    int y = dp[i][j - 1] + 1;
                    // replace word1[i - 1] with word2[j - 1]
                    int z = dp[i - 1][j - 1] + 1;
                    dp[i][j] = Math.min(x, y);
                    dp[i][j] = Math.min(dp[i][j], z);
                }
            }
        }
        return dp[len1][len2];
    }
}
原文地址:https://www.cnblogs.com/ireneyanglan/p/5980439.html