leetcode 死磕动态规划-入门3

每天坚持刷题!!!
今天继续死磕难题

leetcode 72. 编辑距离

题目描述:
给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
1. 插入一个字符
2. 删除一个字符
3. 替换一个字符

题目分析:
1. 动态规划的题的难点还是如何定义状态转移方程和暂存的数组,对于这一道题而言,暂存的二维数组D[i][j]为word1到第i个字符为止匹配word2到第j个字符为止的所需最小的操作数
2. 状态转移分析如下:首先如果word1[i] == word2[j],那么 D[i][j] == D[i-1][j-1],如果word1[i] != word2[j],那么最小的操作数量可能为D[i-1][j-1] + 1(替换操作),或者D[i][j-1] + 1(删除操作),或者D[i-1][j] + 1(插入操作)这三者的最小值。

def minDistance(word1, word2):
    """
    :type word1: str
    :type word2: str
    :rtype: int
    """
    if not word1 and not word2:
        return 0
    elif not word1:
        return len(word2)
    elif not word2:
        return len(word1)
    temp = [[0 for _ in word2] for _ in word1]
    temp[0][0] = 1 if word1[0] != word2[0] else 0
    for i in xrange(len(word1)):
        for j in xrange(len(word2)):
            if i == j == 0:
                continue
            if i - 1 >=0 and j - 1>=0:
                if word1[i] == word2[j]:
                    temp[i][j] = temp[i-1][j-1]
                else:
                    temp[i][j] = min(temp[i-1][j-1] + 1, temp[i][j-1] + 1, temp[i-1][j] + 1)
            elif i - 1 >= 0:
                if word1[i] == word2[j]:
                    temp[i][j] = i
                else:
                    temp[i][j] = temp[i-1][j] + 1
            elif j - 1 >= 0:
                if word1[i] == word2[j]:
                    temp[i][j] = j
                else:
                    temp[i][j] = temp[i][j-1] + 1
    return temp[-1][-1]

欢迎大家批评指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值