leetcode || 72、Edit Distance
来源:程序员人生 发布时间:2015-04-17 08:51:21 阅读次数:3022次
problem:
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
Hide Tags
Dynamic Programming String
题意:求将字符串word1 转换为word2 所需最小的步数,操作包括插入、替换和删除1个字符
thinking:
(1)求全局最优解,锁定DP法
(2)DP的状态转移公式不好找,有几点是DP法共有的,可以有点启发:1、DP大都借助数组实现递推操作 2、DP法的时间复杂度:1维为O(N),2维:O(M*N)
(3)
如果我们用 i 表示当前字符串 A 的下标,j 表示当前字符串 B 的下标。 如果我们用d[i, j] 来表示A[1, ... , i] B[1, ... , j] 之间的最少编辑操作数。那末我们会有以下发现:
1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i⑴, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i⑴, j - 1], d[i, j - 1], d[i⑴, j]) + 1 if A[i] != B[j] //分别代表替换、插入、删除
code:
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int> > f(word1.size()+1, vector<int>(word2.size()+1));
f[0][0] = 0;
for(int i = 1; i <= word2.size(); i++)
f[0][i] = i;
for(int i = 1; i <= word1.size(); i++)
f[i][0] = i;
for(int i = 1; i <= word1.size(); i++)
for(int j = 1; j <= word2.size(); j++)
{
f[i][j] = INT_MAX;
if (word1[i⑴] == word2[j⑴])
f[i][j] = f[i⑴][j⑴];
f[i][j] = min(f[i][j], f[i⑴][j⑴] + 1); //replace
f[i][j] = min(f[i][j], min(f[i⑴][j], f[i][j⑴]) + 1); //delete or insert
}
return f[word1.size()][word2.size()];
}
};
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠