72. Edit Distance【H】【65】
来源:互联网 发布:linux 写文件命令 编辑:程序博客网 时间:2024/05/22 02:16
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]
0 0
- 72. Edit Distance【H】【65】
- LeetCode----72. Edit Distance(H) 动态规划
- LeetCode 72. Edit Distance
- [LeetCode]72.Edit Distance
- LeetCode --- 72. Edit Distance
- [Leetcode] 72. Edit Distance
- [leetcode] 72.Edit Distance
- 72. Edit Distance
- [leetcode] 72.Edit Distance
- 72. Edit Distance
- Leetcode 72. Edit Distance
- 72. Edit Distance
- LeetCode 72. Edit Distance
- leetcode 72. Edit Distance
- LeetCode 72. Edit Distance
- Leetcode 72. Edit Distance
- 72. Edit Distance
- Leetcode:72. Edit Distance
- 【记录】sqlite清空数据表并使id值从1开始(sqlite默认id从1开始)
- swift 基础学习一
- C++文件读写
- HDOJ(HDU) 2520 我是菜鸟,我怕谁(等差数列)
- Five-People:左右滚动的viewpager库说明
- 72. Edit Distance【H】【65】
- linux基础之shell编程(3)-给脚本设置参数
- Activity的启动模式
- 全文索引----solr服务器更新增量索引
- Rsync文件同步备份
- idea16(2016.1.1)下载、安装、破解
- JS 页面跳转和刷新
- 使用贝塞尔曲线算法实现毛笔签名效果
- 文章标题