【Leetcode】72.编辑距离

题目

给定两个单词 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,因为感觉和我们之前的爬楼梯啥的比较相似。这个题目比较为hard主要是,状态转换比较复杂。

定义: dp[i][j] , word1这个字符串的前i个 -> word1这个字符串的前j 个字符,所需要的最小的步数

那么有以下几种情况

word1[i] == word2[j]

不需要做变化,那么 dp[i][j] = dp[i-1,j-1]

word1[i] != word2[j]

我们就需要动用上面那三种操作了:

  • add = dp[i, j-1], 代表插入一个字符
  • delete = dp[i-1, j],代表删除一个字符
  • replace = dp[i-1, j-1],代表替换一个字符
  • dp[i][j] = 1 + min(add, delete, replace)

时间复杂度 o(m * n)

java

class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        // base 
        for (int i = 0; i <= m; i++) {
            dp[i][0] = i;
        }

        for (int j = 0; j <= n; j++) {
            dp[0][j] = j;
        }
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (word1.charAt(i) == word2.charAt(j)) {
                    dp[i + 1][j + 1] = dp[i][j];
                } else {
                    int add = dp[i][j + 1];
                    int delete = dp[i + 1][j];
                    int rep = dp[i][j];
                    dp[i + 1][j + 1] = Math.min(Math.min(add, delete), rep) + 1;
                }
            }
        }
        return dp[m][n];
    }
}

python

class Solution:
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        m = len(word1)
        n = len(word2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            dp[i][0] = i
        for i in range(n + 1):
            dp[0][i] = i
        for i in range(m):
            for j in range(n):
                if word1[i] == word2[j]:
                    dp[i + 1][j + 1] = dp[i][j]
                else:
                    add = dp[i][j + 1]
                    delete = dp[i + 1][j]
                    replace = dp[i][j]
                    dp[i + 1][j + 1] = min(add, delete, replace) + 1
        return dp[m][n]

近期文章

  • 【mysql】mysql系统架构
  • 【Leetcode】71. 简化路径
  • 【Leetcode】70. 爬楼梯

你可能感兴趣的:(Data,structure,and,Algorithm,Database)