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

   这道题是一道典型的使用动态规划来解决的题目。两个单词我们申请一个(m+1)*(n+1)的矩阵,首先对矩阵的第一行和第一列进行初始化,然后从第二行第二个位置开始进行遍历,每次得到最小的编辑数。 这里如果当前两个字母相等的话,直接使其等于上一个字母的编辑数,也即dp[i][j] = dp[i-1][j-1]。但是当两个字母不相等的时候,我们可以从左边上边和右上角选出最小的编辑数在加一,得到当前位置的编辑数,也即dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))+1。这样直到循环遍历到矩阵的末尾。最后一个数字也即是最小编辑距离。时间复杂度为O(m*n),空间复杂度为O(m*n)。
  一般对于动态规划来题目来说,我们除了设置一个(m+1)*(n+1)的矩阵外,还可以使用(n+1)大小的矩阵。这里动态方程还是一样的,只不过这里我们需要处理的细节更多一些。时间复杂度和上面的一样,空间复杂度为O(n+1)。
图示步骤

    解决代码
  第一种空间复杂度为O(m*n)的解法
 class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if not word1 or not word2: # 一个为空直接返回另一个不为空的长度。
return len(word1) if not word2 else len(word2) m, n= len(word1), len(word2)
dp = []
for i in range(m+1): # 构造辅助矩阵
dp.append([0]*(n+1)) for i in range(1, m+1): # 初始化第一列
dp[i][0] = i for j in range(1, n+1): # 初始化第一行
dp[0][j] = j for i in range(1, m+1): # 逐个求解
for j in range(1, n+1):
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-1][j], dp[i][j-1]))+1
return dp[m][n]
  空间复杂度为O(n)的解法
 class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if not word1 or not word2:
return len(word1) if not word2 else len(word2)
m, n= len(word1), len(word2)
dp = [0]*(n+1) # 申请辅助数据
for i in range(1, n+1): # 初始化第一行
dp[i] = i for i in range(1,m+1): # 循环遍历
pre = dp[0] # 记录下dp[0]的值,也即为上面矩阵中dp[i-1][j-1]的值。
dp[0]= i # 给dp[0]赋值为当前单词编辑列的距离,也就是上面的初始化第一列
for j in range(1, n+1):
tem = dp[j] # 相当于记录下dp[i][j-1]的值,
if word1[i-1] == word2[j-1]: # 单词相等的时候
dp[j] = pre
else:
dp[j] = min(pre, min(dp[j-1], dp[j]))+1
pre = tem # 更新值 return dp[-1]

												

【LeetCode每天一题】Edit Distance(编辑距离)的更多相关文章

  1. [LeetCode] Edit Distance 编辑距离

    Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2 ...

  2. [LeetCode] 72. Edit Distance 编辑距离

    Given two words word1 and word2, find the minimum number of operations required to convert word1 to  ...

  3. leetCode 72.Edit Distance (编辑距离) 解题思路和方法

    Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert  ...

  4. Edit Distance编辑距离(NM tag)- sam/bam格式解读进阶

    sam格式很精炼,几乎包含了比对的所有信息,我们平常用到的信息很少,但特殊情况下,我们会用到一些较为生僻的信息,关于这些信息sam官方文档的介绍比较精简,直接看估计很难看懂. 今天要介绍的是如何通过b ...

  5. 【LeetCode】161. One Edit Distance

    Difficulty: Medium  More:[目录]LeetCode Java实现 Description Given two strings S and T, determine if the ...

  6. LeetCode解题报告—— N-Queens && Edit Distance

    1. N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no ...

  7. LeetCode(72) Edit Distance

    题目 Given two words word1 and word2, find the minimum number of steps required to convert word1 to wo ...

  8. 【LeetCode】72. Edit Distance 编辑距离(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 记忆化搜索 动态规划 日期 题目地址:http ...

  9. Java解决LeetCode72题 Edit Distance

    题目描述 地址 : https://leetcode.com/problems/edit-distance/description/ 思路 使用dp[i][j]用来表示word1的0~i-1.word ...

随机推荐

  1. java 读取本地文件并转换为byte数组

    private byte[] InputStream2ByteArray(String filePath) throws IOException { InputStream in = new File ...

  2. IntelliJ IDEA运行eclipse的web项目报错的问题

    用IDEA已经有一段时间了, 由于之前的IDEA版本不支持Tomcat服务器, 所以很长一段时间web项目都是由eclipse开发调试. 今天闲来无事下载了一个最新版的IDEA, 按网上的教程, 尝试 ...

  3. Python学习笔记五

    一. 递归 递归函数: def a (): print ("from b") b() def b(): print("from a ") a() a() 递推和 ...

  4. TortoiseGit安装使用简单教程

    一.简介 TortoiseGit是Tortoise基于git的可视化管理工具.本文即将介绍这个工具的安装和简单使用教程(本文均是基于Windows 64位操作系统). git的管理工具有很多.Tort ...

  5. 为什么用Flow

    Flow 是 facebook 出品的 JavaScript 静态类型检查工具.Vue.js 的源码利用了 Flow 做了静态类型检查,所以了解 Flow 有助于我们阅读源码. flow的工作方式? ...

  6. PHP 闭包函数

    PHP>v5.3闭包函数,闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理 匿名函数也叫闭包函数(closures允许创建一个没有指定没成的函数,最 ...

  7. Linux查看设备命令

    系统 # uname -a # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue # 查看操作系统版本 # cat /proc/cpuinfo # 查看CPU信息 # ho ...

  8. Go的sort接口实现

    package main import ( "fmt" "sort" "time" ) type Track struct { Title ...

  9. Selenium切换窗口,警告框处理,调用JavaScript代码

    多窗口切换 在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作. WebDriver提供了switch_to.window()方法,可以实现在不同的窗口之间切 ...

  10. 2018-2019-1 20189201 《LInux内核原理与分析》第七周作业

    我的愿望是 好好学习Linux 一.书本第六章知识总结[进程的描述和进程的创建] 基础知识1 操作系统内核实现操作系统的三大管理功能,即进程管理功能,内存管理和文件系统.对应的三个抽象的概念是进程,虚 ...