leetcode 72. Edit Distance

link

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

题意: 定义一次编辑可以1.插入一个字符 2. 删除一个字符 3 将一个字符替换为另一个。

求两个字符串的最短编辑距离。

思路:

在切了前面两道匹配之后,这题应该就很容易了吧。

同样定义dp[i][j]为word1[0,i) 匹配word2[0,j)的最小编辑距离。

在转移时,首先我们能看到插入一个字符和删除一个字符是一回事,删除一个字符能完成的插入一个字符也一定能完成,因此可以无视删除操作。(这很重要,这决定了状态只能从前面转移过来)

因此dp[i][j]可以由4个地方转移而来:

1. word1[i-1] == word2[j-1]: 那么直接匹配这俩就行,为dp[i-1][j-1]

2. != 那么随便修改一下,比如修改word1[i-1] = word2[j-1], 为dp[i-1][j-1] + 1

3 在1中插入: 那么就是用word1[0,i) 匹配word2[0,j-1) , 新插入的字符匹配word2[j-1],为dp[i][j-1] + 1

4 在2中插入,同理dp[i-1][j] + 1

求min即可。

为了不特判i=0或者j=0的情况(不然就没有i-1/j-1了) ,预先处理为0的情况 dp[0][i] = i, dp[j][0] = j 。

code:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.length(), len2 = word2.length();
        if(len1 == 0) return len2;
        if(len2 == 0) return len1;
        vector<vector<int>>dp (len1 + 1, vector<int>(len2 + 1, INT_MAX));
        dp[0][0] = 0;
        for(int i = 0; i <= len1; i++){ 
            dp[i][0] = i;
        }
        for(int i = 0; i <= len2; i++){
            dp[0][i] = i;
        }
        for(int i = 1; i <= len1; i++){
            for(int j = 1; j <= len2; j++){
                if(word1[i-1] == word2[j-1]) dp[i][j] = min(dp[i][j], dp[i-1][j-1]);
                // add char in word1
                dp[i][j] = min(dp[i][j], dp[i][j-1] + 1);
                // add char in word2
                dp[i][j] = min(dp[i][j], dp[i-1][j] + 1);
                
                // delete = insert

                // replace char
                dp[i][j] = min(dp[i][j], dp[i-1][j-1] + 1);
            }
        }
        
        return dp[len1][len2];
    }
};
原文地址:https://www.cnblogs.com/bbbbbq/p/7628028.html