Menu
CoddyTech

Edit Distance

困难动态规划python iconjava iconcpp iconc iconjs icon+10

给你两个单词,word1 和 word2。一次编辑可以通过以下三种方式之一更改 word1:在任意位置插入一个字母、删除一个字母,或将一个字母替换为另一个字母。返回将 word1 变成 word2 所需的最少编辑次数。

函数

minDistance(word1: string, word2: string) → integer
word1string
你编辑的单词
word2string
要到达的单词
返回值integer
将 word1 转换为 word2 所需的最少插入、删除和替换次数

约束条件

  • 1 ≤ word1.length ≤ 500
  • 1 ≤ word2.length ≤ 500
  • 这两个单词只包含小写英文字母。

示例

输入
word1 = "spot"word2 = "stop"
输出
2
解释
把 p 换成 t,再把 t 换成 p:spot 变成 stot,然后变成 stop。一次编辑不够,因为这两个单词有两处不同,而且插入或删除都会改变长度。
challenge icon

进阶

你还能在返回编辑次数的同时,返回一个最短的编辑列表吗?

重置代码
def minDistance(word1, word2):
    # 在这里编写代码

测试 #1

测试 #2

测试 #3

参数

word1 = "spot"
word2 = "stop"

预期输出

2