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表,一个是记忆化搜索。效果是memorized search更好。
因为dp填表一定会把O(m*n)的dp表填满。
memorized search走出来的则是一条从起点到终点的线,不会填满整个表。时间退化到O(m+n),变成找路径的时间。
public class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int 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 if(word1.charAt(i-1) == word2.charAt(j-1) ) {  
                    dp[i][j] = dp[i-1][j-1];
                } else {
                    dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
                }
            }
        }
        return dp[m][n];
    }
}
public class Solution {
    int[][] dp;
    
    public int minDistance(String word1, String word2) {
        dp = new int[word1.length()][word2.length()];
        
        return minDistanceHelper(word1, word2, 0, 0);
    }
    
    private int minDistanceHelper(String word1, String word2, int index1, int index2) {
        if (index1 == word1.length()) return word2.length() - index2;
        if (index2 == word2.length()) return word1.length() - index1;
        
        if (dp[index1][index2] > 0) return dp[index1][index2];
        
        int result;
        if (word1.charAt(index1) == word2.charAt(index2)) {
            result = minDistanceHelper(word1, word2, index1+1, index2+1);
        } else {
            // replace char "abac" , "abdc" replace 'a' with 'd' 
            result = 1 + minDistanceHelper(word1, word2, index1+1, index2+1);
            
            // insert char into word1    "abc" , "abdc" insert 'd'
            result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1, index2+1));
            
            // delete char from word1    "abdc" , "abc"  delete 'd'
            result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1+1, index2));
        }
        
        dp[index1][index2] = result;
        return result;
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。