动态规划之Leetcode 72. Edit Distance
2018-01-26 14:47
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
意思是
给两个单词,求从单词1变换到单词2的最小步数,变换的操作有 增加字符,删除字符和替换字符三种。
比如从”apaed” 到 “dapade” 需要3步。
分析
这道题实际上是一个动态规划题,我们用d(i,j)表示第一个单词的i个字符变换到第二个单词j个字符的步骤,显然d(i,0)=i,d(0,j)=j,都只需要依次删除相应的字符。那么d(i+1,j+1)有几种可能性呢?
首先从d(i+1,j)到d(i+1,j+1)只是第二个单词增加了一个字符,即d(i+1,j+1)=d(i+1,j)+1
从d(i,j+1)到d(i+1,j+1)是第一个单词多了一个字符,那么只需要增加在d(i,j+1)的基础上删除一个字符的步骤,即d(i+1,j+1)=d(i,j+1)+1
从d(i,j)到d(i+1,j+1),如果第一个单词的第i+1个字符和第二个单词的j+1个字符相等,则d(i+1,j+1)=d(i,1),若不相等,则需要在d(i,j)的基础上把第i+1个字符替换为j+1个字符。即d(i+1,j+1)=d(i,j)+1
以上三种情况都有可能,最终d(i+1,j+1)取三种情况的最小值
举个栗子:
从字符串”dabca”变换到”bcddc”.
我们写出d(i,j)矩阵
d | a | b | c | a | ||
---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | |
b | 1 | 1 | 2 | 2 | 3 | 4 |
c | 2 | 2 | 2 | 3 | 2 | 3 |
d | 3 | 2 | 3 | 3 | 3 | 3 |
d | 4 | 3 | 3 | 4 | 4 | 4 |
c | 5 | 4 | 4 | 4 | 4 | 5 |
代码
python代码如下class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ len1,len2 = len(word1),len(word2) if len1 == 0 or len2 == 0: return max(len1, len2) dist = [[0 for i in range(len2+1)] for j in range(len1+1)] for i in range(len1+1): dist[i][0] = i for j in range(len2+1): dist[0][j] = j for i in range(len1): for j in range(len2): if word1[i] == word2[j]: dist[i+1][j+1]=dist[i][j] else: dist[i+1][j+1]=min(dist[i][j],dist[i][j+1],dist[i+1][j])+1 return dist[len1][len2]
相关文章推荐
- LeetCode 70. Climbing Stairs 自顶向下记忆化搜索,自底向上重叠子问题动态规划
- 不同的子序列(leetcode hard)动态规划
- leetcode 413. Arithmetic Slices 等差子数组 + 一个很简单DP动态规划做法
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- [LeetCode]wildcard matching通配符实现之动态规划
- leetcode 第53题 Maximum Subarray:动态规划的活用
- LeetCode中的动态规划题目解答(2)
- Leetcode-198_ House Robber-典型动态规划-【C++】
- 动态规划第五讲——leetcode上的题目动态规划汇总(上)
- leetcode 第32题:动态规划思想与堆栈的灵活使用
- leetcode 322. Coin Change 类似背包问题 + 很简单的动态规划DP解决
- LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV
- 从 LeetCode 279 实践动态规划
- LeetCode动态规划思想:Best Time to Buy and Sell Stock III
- 动态规划入门级教学(leetcode)53.Maximum Subarray
- leetcode 446. Arithmetic Slices II - Subsequence 等差序列的数量 + 一个很值得学习的DP动态规划做法
- LeetCode之“动态规划”:Unique Binary Search Trees && Unique Binary Search Trees II
- [LeetCode] Scramble String -- 三维动态规划的范例
- LeetCode题目:Unique Binary Search Trees,一维动态规划
- 动态规划第六讲——leetcode上的动态规划汇总(下)