Edit Distance

1,题目要求

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')

给定两个单词word1和word2,找到将word1转换为word2所需的最小操作数。

您对单词允许以下3个操作:

  1. 插入一个字符
  2. 删除一个字符
  3. 替换一个字符

2,题目思路

对于这道题,找到将word1转化为word2的最小操作数。

在这个问题上,我们使用动态规划的策略来实现。

在运用DP上,我们定义:

  • dp[i][j]:将word1[0..i)转换为word2[0...j)所需要的最小的步骤数。

对于基础情况——将一个字符串转换为一个空串(使用删除操作),因此我们有:

  • dp[i][0] = i
  • dp[0][j] = j

而之后,将word1[0..i)转换为word2[0...j)时,假如我们已经知道了word1[0..i-1)转换为word2[0...j-1)的最小操作数——dp[i-1][j-1],则:
假如word1[i - 1] == word2[j - 1],则根本不需要转换,直接有:dp[i][j] = dp[i - 1][j - 1]

假如word1[i - 1] != word2[j - 1],则此时有三种情况:

  1. 将word1[i - 1]替换为word2[j - 1]。(dp[i][j] = dp[i - 1][j - 1] + 1
  2. 如果word1[0…i - 1) = word2[0…j),则此时我们删除word1[i - 1] 。(dp[i][j] = dp[i - 1][j] + 1
  3. 如果word1[0…i) + word2[j - 1] = word2[0…j),将word2[j - 1]插入到word1[0…i)。(dp[i][j] = dp[i][j - 1] + 1

从上面的三点中,总结有:dp[i][j] = dp[i][j - 1] + 1

由此,得到了dp[i][j]的计算方法,也就得到了DP的解法。

3,代码实现

static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        vector<vector<int>> dp(m+1, vector<int>(n+1));
        
        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++){
                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][j-1], dp[i-1][j])) + 1;
                }
            }
        return dp[m][n];
    }
};

你可能感兴趣的:(C++OJ,Self-Culture,LeetCode,LeetCode,Top100,Liked,Question,Top,100,Liked,Questions)