博客
关于我
LeetCode 72. 编辑距离 python
阅读量:632 次
发布时间:2019-03-14

本文共 1494 字,大约阅读时间需要 4 分钟。

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’)

1.递归 自顶向下(超时)(添加缓存修饰器通过)

class Solution:	# 缓存修饰器	@lru_cache(None)    def minDistance(self, word1: str, word2: str) -> int:        if word1 == '' or word2 == '':            return max(len(word1), len(word2))        if word1[-1] == word2[-1]:            return self.minDistance(word1[:-1], word2[:-1])        return min(self.minDistance(word1[:-1], word2), self.minDistance(word1, word2[:-1]), self.minDistance(word1[:-1], word2[:-1])) + 1

2.动态规划 自底向上

class Solution:    def minDistance(self, word1: str, word2: str) -> int:        n1 = len(word1)        n2 = len(word2)        dp = [[0] * (n2 + 1) for _ in range(n1 + 1)]        for i in range(1, n1 + 1):            dp[i][0] = i        for i in range(1, n2 + 1):            dp[0][i] = i        for i in range(1, n1 + 1):            for j in range(1, n2 + 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], dp[i][j - 1], dp[i - 1][j - 1]) + 1        return dp[-1][-1]

转载地址:http://vrxoz.baihongyu.com/

你可能感兴趣的文章
Netty 异步任务调度与异步线程池
查看>>
Netty 的 Handler 链调用机制
查看>>
Netty 编解码器详解
查看>>
Netty 解决TCP粘包/半包使用
查看>>
Netty 调用,效率这么低还用啥?
查看>>
Netty 高性能架构设计
查看>>
Netty+Protostuff实现单机压测秒级接收35万个对象实践经验分享
查看>>
Netty+SpringBoot+FastDFS+Html5实现聊天App详解(一)
查看>>
netty--helloword程序
查看>>
netty2---服务端和客户端
查看>>
Netty5.x 和3.x、4.x的区别及注意事项(官方翻译)
查看>>
netty——bytebuf的创建、内存分配与池化、组成、扩容规则、写入读取、内存回收、零拷贝
查看>>
netty——Channl的常用方法、ChannelFuture、CloseFuture
查看>>
netty——EventLoop概念、处理普通任务定时任务、处理io事件、EventLoopGroup
查看>>
netty——Future和Promise的使用 线程间的通信
查看>>
netty——Handler和pipeline
查看>>
Vue输出HTML
查看>>
netty——黏包半包的解决方案、滑动窗口的概念
查看>>
Netty中Http客户端、服务端的编解码器
查看>>
Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息
查看>>