编辑距离

215 阅读2分钟

动态规划问题

给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符
删除一个字符
替换一个字符

示例 1:

输入:word1 = "horse", word2 = "ros" 输出:3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e')

示例 2:

输入:word1 = "intention", word2 = "execution" 输出:5 解释: intention -> inention (删除 't') inention -> enention (将 'i' 替换为 'e') enention -> exention (将 'n' 替换为 'x') exention -> exection (将 'n' 替换为 'c') exection -> execution (插入 'u')

题目链接

题解

dp数组dp[i][j]表示word1到i位置转换为word2到j位置需要的最少步数

dp方程:当word1[i] == word2[j]时,dp[i][j] = dp[i-1][j-1]

当word1[i] != word2[j]时,dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]) + 1;

dp[i-1][j-1]为更换字母,dp[i-1][j]为删除,dp[i][j-1]为插入

实际上并不用考虑dp[i-1][j-1],dp[i-1][j],dp[i][j-1]代表的操作,这里只需要对三种状态进行穷举即可,而三种状态的全集就是dp[i-1][j-1],dp[i-1][j],dp[i][j-1]。

注意:对于第一行(下标0)和第一列(下标0)的数组元素的初始化要单独处理,word1 0位置到word2 i 位置每次都是插入操作,因此都是+1,列操作也一样。

c++代码:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int size1 = word1.size();
        int size2 = word2.size();
        int dp[size1+1][size2+1];
        memset(dp,0,sizeof(dp));
        for(int j=1;j<=size2;j++){
            dp[0][j] = dp[0][j-1] + 1;
        }
        for(int i=1;i<=size1;i++){
            dp[i][0] = dp[i-1][0] + 1;
        }
        for(int i=1;i<=size1;i++){
            for(int j=1;j<=size2;j++){
                if(word1[i-1] == word2[j-1]){
                    dp[i][j] = dp[i-1][j-1];
                }else{
                    dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])) + 1;
                }
            }
        }
        return dp[size1][size2];
    }
};

java代码:

package dp.edit_distance;

public class edit_distance {

    public int minDistance(String word1,String word2){
        int length1 = word1.length();
        int length2 = word2.length();
        int[][] dp = new int[length1 + 1][length2 + 1];
        for(int j = 1; j <= length2 ; j++){
            dp[0][j] = dp[0][j - 1] + 1;
        }
        for(int i = 1; i <= length1 ; i++){
            dp[i][0] = dp[i - 1][0] + 1;
        }
        for(int i = 1; i <= length1 ; i++){
            for(int j = 1; j <= length2; j++){
                if(word1.charAt(i-1) == word2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1];
                }else {
                    dp[i][j] = Math.min(Math.min(dp[i-1][j-1],dp[i][j-1]),dp[i-1][j]) + 1;
                }
            }
        }
        return dp[length1][length2];
    }

    public static void main(String[] args) {
        String str1 = "intention";
        String str2 = "execution";
        edit_distance example = new edit_distance();
        System.out.println("" + example.minDistance(str1,str2));
    }
}