72. Edit Distance【H】【65】

157 篇文章 0 订阅
42 篇文章 0 订阅

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

Subscribe to see which companies asked this question


问题:找出字符串的编辑距离,即把一个字符串s1最少经过多少步操作变成编程字符串s2,操作有三种,添加一个字符,删除一个字符,修改一个字符

 

解析:

首先定义这样一个函数——edit(i, j),它表示第一个字符串的长度为i的子串到第二个字符串的长度为j的子串的编辑距离。

显然可以有如下动态规划公式:

  • if i == 0 且 j == 0,edit(i, j) = 0
  • if i == 0 且 j > 0,edit(i, j) = j
  • if i > 0 且j == 0,edit(i, j) = i

  • if i ≥ 1  且 j ≥ 1 ,edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) },当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,f(i, j) = 1;否则,f(i, j) = 0。
class Solution(object):
    def minDistance(self, word1, word2):
        s1 = word1
        s2 = word2

        l1 = len(s1) + 1
        l2 = len(s2) + 1

        if s1 == '' or s2 == '':
            return max(l1,l2) - 1

        t = [0]*l1
        res =[0] * l2

        for i in xrange(l2):
            res[i] = t[:]

        for i in xrange(l1):
            res[0][i] = i

        for i in xrange(l2):
            res[i][0] = i

        for i in xrange(1,l2):
            for j in xrange(1,l1):
                res[i][j] = min(res[i-1][j] + 1,res[i][j-1] + 1,res[i-1][j-1] + (s1[j - 1] != s2[i - 1 ]))

        return res[-1][-1]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值