微信公众号

72. Edit Distance

Description:

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)递归解法

从两个字符串的最后的位置开始考虑:

  • 如果最后两个字符(i,j)相等,最后两个字符就不要配对,所以等于minDistance(s1[0..i-1],s2[0...j-1]);
  • 如果最后两个字符不相等: 说明要编辑,具体可以分为三种情况:

a. 如果 s1[i-1]和s2[j]可以配对,那我就删除s1[i]即可(删除);

b. 如果 s1[i]和s2[j-1]可以配对,那我就在s1的后面加上s2[j]即可(插入);

c. 如果 s1[i-1]和s2[j-1]可以配对,那我就把s1[i]修改成s2[j]即可;

上面图片来源: https://blog.csdn.net/zxzxzx0119/article/details/82054807

class Solution:def minDistance(self, word1: str, word2: str) -> int:l1 = len(word1)l2 = len(word2)def tryMinDistance(i, j):if i == -1:return j + 1elif j == -1:return i + 1elif (word1[i] == word2[j]):return tryMinDistance(i - 1, j - 1)else:return (1 + min(tryMinDistance(i - 1, j - 1),  # replace itryMinDistance(i - 1, j),  # delete itryMinDistance(i, j - 1)  # add i+1 index))return tryMinDistance(l1 - 1, l2 - 1)so = Solution()
# test 1
word1 = "horse"
word2 = "ros"# test 2
# word1 = "intention"
# word2 = "execution"# test 3
# word1 = "dinitrophenylhydrazine"
# word2 = "benzalphenylhydrazone"# test 4
# word1 = ""
# word2 =""
print(so.minDistance(word1, word2))

(2)记忆化递归法

下面代码没有AC,代码有问题。

class Solution:def minDistance(self, word1: str, word2: str) -> int:l1 = len(word1)l2 = len(word2)dp = [[-1] * (l2)] * (l1)def tryMinDistance(i, j):if i == -1:return j + 1elif j == -1:return i + 1elif dp[i][j] != -1:return dp[i][j]elif (word1[i] == word2[j]):dp[i][j] = tryMinDistance(i-1, j-1)else:dp[i][j] = 1 + min(tryMinDistance(i-1, j-1),    # replace itryMinDistance(i-1, j),  # delete itryMinDistance(i, j-1)   # add i+1 index)print(dp)return dp[i][j]return tryMinDistance(l1-1, l2-1)so = Solution()
# test 1
word1 = "horse"
word2 = "ros"# test 2
# word1 = "intention"
# word2 = "execution"# test 3
# word1 = "dinitrophenylhydrazine"
# word2 = "benzalphenylhydrazone"# test 4
# word1 = ""
# word2 =""
print(so.minDistance(word1, word2))

上面代码总是在第一个测试用例中出错,得到结果是4。经过好长时间分析测试,发现是以下代码有问题:

dp = [[None] * (len(word2)) for _ in range(len(word1))]
print(dp)dp1 = [[None] * (len(word2))] * (len(word1))
print(dp1)

上面两种方式初始化列表,虽然得到结果形式上是一致的,却能造成不同的结果。目前还没想清楚,这两种方式的不同。

20190603补充:

上面两种初始化方式在更新列表数据时有差别,我们来看两个例子,感受一下:

例1:

dp = [[1] * 2] * 4
print(dp)
dp[0][1]=5
print(dp)

结果:

例2:

dp = [[1] * 2 for _ in range(4)]
print(dp)
dp[0][1]=5
print(dp)

结果:

已经AC的代码,如下:

class Solution:def minDistance(self, word1: str, word2: str) -> int:l1 = len(word1)l2 = len(word2)dp = dp = [[-1] * (len(word2)) for _ in range(len(word1))]def tryMinDistance(i, j):if i == -1:return j + 1elif j == -1:return i + 1elif dp[i][j] != -1:return dp[i][j]elif (word1[i] == word2[j]):dp[i][j] = tryMinDistance(i - 1, j - 1)else:dp[i][j] = 1 + min(tryMinDistance(i - 1, j - 1),  # replace itryMinDistance(i - 1, j),  # delete itryMinDistance(i, j - 1)  # add i+1 index)return dp[i][j]return tryMinDistance(l1 - 1, l2 - 1)so = Solution()
# test 1
# word1 = "horse"
# word2 = "ros"# test 2
# word1 = "intention"
# word2 = "execution"# test 3
# word1 = "dinitrophenylhydrazine"
# word2 = "benzalphenylhydrazone"# test 4
# word1 = ""
# word2 =""# test 5
word1 = "sea"
word2 = "eat"
print(so.minDistance(word1, word2))

(3)动态规划解法

上面图片来源:https://blog.csdn.net/zxzxzx0119/article/details/82054807

二维动态规划就是使用一个二维数组从左到右,从上到下来递归出最后的答案,注意几点:

  • dp数组的大小 dp[chs1.length + 1] [chs2.length + 1],因为一开始是空串" ",所以要多开一个;
  • 一开始初始化第一行和第一列,第一行表示的是chs1为空字符串""变成chs2要添加chs2长度的次数。第一列表示的是chs2为空字符串""变成chs1需要添加chs1长度的次数。

 已经AC的代码:

class Solution:def minDistance(self, word1: str, word2: str) -> int:l1 = len(word1)l2 = len(word2)dp = [[0] * (l2+1) for _ in range(l1+1)]# print(dp)for i in range(l1+1):dp[i][0] = ifor j in range(l2+1):dp[0][j] = jfor i in range(1, l1+1):for j in range(1, l2+1):if word1[i - 1] == word2[j - 1]:c  = 0else:c = 1dp[i][j] = min(dp[i-1][j-1]+c, min(dp[i][j-1], dp[i-1][j])+1)return dp[l1][l2]

Reference:

【1】https://leetcode.com/problems/edit-distance/

【2】花花酱 LeetCode 72. Edit Distance - 刷题找工作 EP87

【3】LeetCode - 72. Edit Distance(编辑距离问题)(三个依赖的滚动优化)

【4】https://blog.csdn.net/zxzxzx0119/article/details/82054807

【LeetCode】72. Edit Distance相关推荐

  1. 【LeetCode】849. Maximize Distance to Closest Person

    [LeetCode]849. Maximize Distance to Closest Person 849. Maximize Distance to Closest Person Easy In ...

  2. 【LeetCode】849. Maximize Distance to Closest Person 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  3. 【LeetCode】461. Hamming Distance (java实现)

    2019独角兽企业重金招聘Python工程师标准>>> 原题链接 https://leetcode.com/problems/hamming-distance/ 原题 The Ham ...

  4. 【LeetCode】汉明距离(Hamming Distance)

    这道题是LeetCode里的第461道题. 题目描述: 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目. 给出两个整数 x 和 y,计算它们之间的汉明距离. 注意: 0 ≤ x,  ...

  5. 【LeetCode】72. 编辑距离 【动态规划】

    题目链接:https://leetcode-cn.com/problems/edit-distance/ 题目描述 给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word ...

  6. 【LeetCode】字符串 string(共112题)

    [3]Longest Substring Without Repeating Characters (2019年1月22日,复习) [5]Longest Palindromic Substring ( ...

  7. 【重点!记忆化递归+DP】LeetCode 72. Edit Distance

    LeetCode 72. Edit Distance 参考链接:https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit ...

  8. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  9. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  10. 【LeetCode】【HOT】739. 每日温度(栈)

    [LeetCode][HOT]739. 每日温度 文章目录 [LeetCode][HOT]739. 每日温度 package hot;import java.util.ArrayDeque; impo ...

最新文章

  1. margin-top失效的解决方法
  2. 【转】使用genstring和NSLocalizedString实现App文本的本地化
  3. 浏览器渲染机制面试_面试官不讲码德,问我Chrome浏览器的渲染原理(6000字长文)...
  4. 条件随机场 python_用条件随机场做网络小说命名实体识别
  5. 焦作师范高等专科学校对口计算机分数线,焦作师范高等专科学校录取分数线2018...
  6. 评审专家:基金本子“瘦”点好
  7. 数据结构与算法分析(七)——C++实现平衡二叉树
  8. msxml3.dll 错误 '80072efd' A connection with the server could not be established
  9. ubuntu18.04系统无法正常连接网络解决办法
  10. 交叉谱分析——Python
  11. Z-Stack 的应用层参数修改
  12. 局域网内2台ubuntu电脑共享鼠标键盘
  13. OpenCV中的Shi-Tomasi角点检测器
  14. 3D角色硬表面建模技巧与思路分享【案例解析】
  15. 条形码打印 EPL命令解释
  16. DALLE·2(Hierarchical Text-Conditional Image Generation with CLIP Latents)
  17. micropython esp32手册_编译micropython遇到的几个问题(ESP32平台)
  18. 多视角探析贝塞尔曲线匀速化技术、实现及其应用
  19. WEB 视频开发-主流协议 HLS DASH
  20. LightningChart解决方案:XY和3D图表(Polymer Char GPC-IR®-工程案例)

热门文章

  1. html怎么设置字体的背景颜色,html怎样设置字体的背景颜色?
  2. 像素值/DN值/数字量化值
  3. 蜂鸣器音乐代码 天空之城_歌单 | 音乐拥有魔力
  4. android手机系统怎么刷机包,安卓系统怎么刷机?安卓系统手机通用刷机教程
  5. 使用SPSS 进行两组独立样本的t检验、F检验、显著性差异、计算p值
  6. 网络领域 ——《Adaptable Switch: A Heterogeneous Switch Architecture for Network-Centric Computing》
  7. python基础教程第三版pdf 脚本之家-一篇不错的Python入门教程
  8. 花两年时间去面试一个人——给准备面试的启发
  9. MATLAB各个产品概述----哪些产品需要安装?哪些产品不需要安装?阅完了然
  10. 常见路由器默认用户名和密码