【Leetcode】72. Edit Distance(动态规划)(2019拼多多笔试)(重点)

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

题目大意:

给出两个字符串,我们需要通过三种操作1、替换;2、插入;3、删除。通过最少的操作步骤来将word1变成word2。

解题思路:

本题是很隐晦的DP,但是我们可以从三种操作看出动态规划的迹象。先不做解释。

4/22:我们可以将第一列、第一行的初始化的行为看成如果从空字符串经过操作到当前目标需要的步数。而每个位置的初始化,如果相同则直接取上一步的步数,即对角线上的值;如果不相同则出现了给出的三种情况,(1)从对角线出发,即上一个答案中插入一个新的字符,使其满足当前的目标字符串;(2)从原有的字符串出发,即删除当前位置,使其满足当前的目标字符串;(3)从目标字符串出发,即替换当前位置,使其满足当前的目标字符串;

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        vector> ans(m+1, vector(n+1, 0));
        for(int i = 1;i<=m;i++){
            ans[i][0] = i;
        }
        for(int i = 1;i<=n;i++){
            ans[0][i] = i;
        }
        for(int i = 1;i<=m;i++){
            for(int j = 1;j<=n;j++){
                if(word1[i-1] == word2[j-1]){
                    ans[i][j] = ans[i-1][j-1];
                }else{
                    ans[i][j] = min(ans[i-1][j-1], min(ans[i-1][j], ans[i][j-1])) +1;
                }
            }
        }
        return ans[m][n];
    }
};

 

你可能感兴趣的:(【LeetCode】刷题记录)