72. Edit Distance - jiejackyzhang/leetcode-note GitHub Wiki
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
解题思路为Dynamic Programming。
令dp[i][j]表示min edit distance between word1[1..i] and word2[1..j]。 则有三种操作:
insert: dp[i][j-1] + 1
delete: dp[i-1][j]+1
replace: dp[i-1][j-1]+(0 if word1[i-1] == word2[j-1] else 1)
 
dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+(0 if word1[i-1] == word2[j-1] else 1))
base cases为:
dp[i][0] = i, dp[0][j] = j
##Approach 1: space O(mn)
public class Solution {
    public int minDistance(String word1, String word2) {
        if(word1.equals(word2)) return 0;
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m+1][n+1];
        dp[0][0] = 0;
        for(int i = 1; i <= m; i++) dp[i][0] = i;
        for(int j = 1; j <= n; j++) dp[0][j] = j;
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                dp[i][j] = Math.min(Math.min(dp[i-1][j] + 1, dp[i][j-1] + 1), word1.charAt(i-1) == word2.charAt(j-1) ? dp[i-1][j-1] : dp[i-1][j-1] + 1);
            }
        }
        return dp[m][n];
    }
}
##Approach 2: space O(n) 可以将上面的table压缩为一行row,即dp每次都记录当前i下的dp[1..n],在下一个i时,dp[j]表示的即为dp[i-1][j]。 用一个变量prev来记录dp[i-1][j-1]。
public class Solution {
    public int minDistance(String word1, String word2) {
        if(word1.equals(word2)) return 0;
        int m = word1.length();
        int n = word2.length();
        int[] dp = new int[n+1];
        dp[0] = 0;
        for(int j = 1; j <= n; j++) dp[j] = j;
        for(int i = 1; i <= m; i++) {
            int prev = dp[0];
            dp[0]++;
            for(int j = 1; j <= n; j++) {
                int temp = dp[j];
                dp[j] = Math.min(Math.min(dp[j-1] + 1, dp[j] + 1), word1.charAt(i-1) == word2.charAt(j-1) ? prev : prev + 1); 
                prev = temp;
            }
        }
        return dp[n];
    }
}