LeetCode in Python 72. Edit Distance (编辑距离)

本文介绍了编辑距离的基本思想,如何通过动态规划转化为求解最小路径和问题,以Python实现了一个Solution类,演示了如何计算两个单词之间的最少操作次数,同时提及了最小路径和问题在LeetCode中的应用。

编辑距离的基本思想很直观,即不断比较两个单词每个位置的元素,若相同则比较下一个,若不同则需要考虑从插入、删除、替换三种方法中选择一个最优的策略。涉及最优策略笔者最先想到的即是动态规划的思想,将两个单词的位置对应放在矩阵中即可将其转化为类似求解最小路径和的问题。

示例:

图1 编辑距离输入输出示意图 

代码:

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        cost = [[float("inf")] * (len(word2) + 1) for _ in range(len(word1) + 1)]
        for i in range(len(word1) + 1):
            cost[i][len(word2)] = len(word1) - i
        for j in range(len(word2) + 1):
            cost[len(word1)][j] = len(word2) - j
        for i in range(len(word1) - 1, -1, -1):
            for j in range(len(word2) -1, -1, -1):
                if word1[i] == word2[j]:
                    cost[i][j] = cost[i + 1][j + 1]
                else:
                    cost[i][j] = 1 + min(cost[i + 1][j], cost[i][j + 1], cost[i + 1][j + 1])
        return cost[0][0]

解释:

1)cost为记录最少操作数的二维数组,若word2为空,word1变为word2需要删除word1中所有字符,即操作数为len(word1)。同理,若word1为空,word1变为word2需要插入word2中所有字符,即操作数为len(word2):

        for i in range(len(word1) + 1):

                cost[i][len(word2)] = len(word1) - i

        for j in range(len(word2) + 1):

                cost[len(word1)][j] = len(word2) - j

2)对于cost其他位置的最少操作数,则根据动态规划的思想,若两个位置对应的字符相同,则指针均向后移位,反之,则需要从插入、删除、替换三种操作中选择一种,选择三种操作后所需最少操作数的方法:

        for i in range(len(word1) - 1, -1, -1):

               for j in range(len(word2) - 1, -1, -1):

                       if word1[i] == word2[j]:

                              cost[i][j] = cost[i + 1][j + 1]

                       else:

                             cost[i][j] = 1 + min(cost[i + 1][j], cost[i][j + 1], cost[i + 1][j + 1])

3)算法图解

图2 编辑距离算法图解 

另附上最小路径和解决方法:

LeetCode 64 in Python. Minimum Path Sum (最小路径和)-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值