LeetCode算法系列:72. Edit Distance

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82770165

题目描述;

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

算法实现:

这个问题采用动态规划的方法实现,这道题我们需要维护一个二维的数组md,其中md[i][j]表示从word1的前i个字符转换到word2的前j个字符所需要的步骤。对第一行和第一列比较简单,因为在这种情况下总有一个单词是一个字符的。关键在于递推关系

md[i][j] = word1[i] == word2[j] ? md[i - 1][j - 1] : min(min(md[i][j - 1], md[i - 1][j]),md[i - 1][j - 1]) + 1;

当word1[i] == word2[j]时,md[i][j] = md[i - 1][j - 1],其他情况时,md[i][j]是其左,左上,上的三个值中的最小值加,具体如下:

//动态规划,关键在于寻找递推关系
class Solution {
public:
    int minDistance(string word1, string word2) {
        if(word1.empty() && word2.empty())return 0;
        if(word1.empty() || word2.empty())return max(word1.length(), word2.length());
        int n1 = word1.length();
        int n2 = word2.length();
        vector<vector<int>> md(n1,vector<int>(n2));
        md[0][0] = word1[0] == word2[0] ? 0 : 1;
        for(int i = 1; i < n2; i ++)
            md[0][i] = word1[0] == word2[i] ? i : md[0][i - 1] + 1;
        for(int i = 1; i < n1; i ++)
            md[i][0] = word1[i] == word2[0] ? i : md[i - 1][0] + 1;
        for(int i = 1; i < n1; i ++)
            for(int j = 1; j < n2; j ++)
                md[i][j] = word1[i] == word2[j] ? md[i - 1][j - 1] : min(min(md[i][j - 1], md[i - 1][j]),md[i - 1][j - 1]) + 1;
        return md[n1 - 1][n2 - 1];
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82770165