当前位置:网站首页>72. 编辑距离
72. 编辑距离
2022-07-01 03:23:00 【Sun_Sky_Sea】
72. 编辑距离
原始题目链接:https://leetcode.cn/problems/edit-distance/
给你两个单词 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’)
提示:
0 <= word1.length, word2.length <= 500
word1 和 word2 由小写英文字母组成
解题思路:
定义dp[i][j]的含义为:word1的前i个字符和word2的前j个字符的编辑距离。就是word1的前i个字符,变成word2的前j个字符,最少需要这么多步。如果其中一个字符串是空串,那么编辑距离是另一个字符串的长度;两个串都不空时,dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+int(word1[i]!=word2[j])):
例如,word1 = “abcde”, word2 =“fgh”,我们现在算这俩字符串的编辑距离,就是找从word1,最少多少步,能变成word2?那就有三种方式:知道"abcd"变成"fgh"多少步(假设X步),那么从"abcde"到"fgh"就是"abcde"->“abcd”->“fgh”。(一次删除,加X步,总共X+1步)
知道"abcde"变成“fg”多少步(假设Y步),那么从"abcde"到"fgh"就是"abcde"->“fg”->“fgh”。(先Y步,再一次添加,加X步,总共Y+1步)
知道"abcd"变成“fg”多少步(假设Z步),那么从"abcde"到"fgh"就是"abcde"->“fge”->“fgh”(替换)。
代码实现:
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
if m * n == 0:
return m + n
# 定义dp[i][j]:word1到i的字符 变换成 word2[j] 的编辑距离
dp = [[0] * (n + 1) for _ in range(m + 1)]
# 初始化dp:word1为空或者word2为空,那么转换的最少步数
# 就是word1或word2的长度
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# 根据dp[i - 1][j] dp[i][j - 1] dp[i - 1][j - 1]
# 计算dp[i][j]的值
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + int(word1[i - 1] != word2[j - 1]))
return dp[m][n]
参考文献:
https://leetcode.cn/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode-solution/
边栏推荐
- Leetcode 128 longest continuous sequence (hash set)
- md5sum操作
- What happens when a function is called before it is declared in C?
- [深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
- [deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
- JS daily development tips (continuous update)
- IPv4和IPv6、局域网和广域网、网关、公网IP和私有IP、IP地址、子网掩码、网段、网络号、主机号、网络地址、主机地址以及ip段/数字-如192.168.0.1/24是什么意思?
- IPv4 and IPv6, LAN and WAN, gateway, public IP and private IP, IP address, subnet mask, network segment, network number, host number, network address, host address, and IP segment / number - what does
- 快速筛选打卡时间日期等数据:EXCEL筛选查找某一时间点是否在某一时间段内
- Design of serial port receiving data scheme
猜你喜欢

idea插件备份表

访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载

Appium fundamentals of automated testing - basic principles of appium

The preorder traversal of leetcode 144 binary tree and the expansion of leetcode 114 binary tree into a linked list

Ultimate dolls 2.0 | encapsulation of cloud native delivery

RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs

Blueprism registration, download and install -rpa Chapter 1

Unexpected token o in JSON at position 1 ,JSON解析问题

服务器渲染技术jsp

详解Spark运行模式(local+standalone+yarn)
随机推荐
Use of comment keyword in database
What happens when a function is called before it is declared in C?
Nacos
The preorder traversal of leetcode 144 binary tree and the expansion of leetcode 114 binary tree into a linked list
访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
Detailed list of errors related to twincat3 ads of Beifu
衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
Bilinear upsampling and f.upsample in pytorch_ bilinear
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
岭回归和lasso回归
[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)
FCN全卷積網絡理解及代碼實現(來自pytorch官方實現)
Online public network security case nanny level tutorial [reaching out for Party welfare]
网页不能右键 F12 查看源代码解决方案
How to display scrollbars on the right side of the background system and how to solve the problem of double scrollbars
10、Scanner. Next() cannot read spaces /indexof -1
Random seed torch in deep learning manual_ seed(number)、torch. cuda. manual_ seed(number)
Leetcode 31 next spread, leetcode 64 minimum path sum, leetcode 62 different paths, leetcode 78 subset, leetcode 33 search rotation sort array (modify dichotomy)
pytorch训练深度学习网络设置cuda指定的GPU可见