您的位置:首页 > 其它

72. Edit Distance【H】【65】

2016-05-09 16:24 363 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: