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。
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]
相关文章推荐
- bzoj 1880: [Sdoi2009]Elaxia的路线(拓扑排序+spfa)
- HDOJ(HDU) 2520 我是菜鸟,我怕谁(等差数列)
- nginx学习笔记三(nginx启动框架的处理流程)
- Activity的启动模式
- js事件监听器用法实例详解
- HDOJ(HDU) 2520 我是菜鸟,我怕谁(等差数列)
- 视频自动播放
- Day1作业1:登陆接口(加入日志、注册功能)
- Many to many relationships&Assignment
- POJ 1182 食物链 并查集
- QNX的音频应用实例
- STL:二级空间配置器浅谈
- Mysql 实现 Rownum() 排序后根据条件获取名次
- hdu 1598(最小生成树)
- C#和C++除了语法上的差别外,还有什么其他的区别
- Html/JS实现页面的折叠
- 跳转到系统设置
- stdio.h
- iOS 网络请求 NSURLSession
- ElasticSearch 简单入门helloworld