您的位置:首页 > 其它

LeetCode 72. Edit Distance

2017-04-16 14:54 274 查看
这道题是算法课程中刚刚讲过的,是一道经典的动态规划的问题。在编辑距离中定义了3种操作:

- 插入: 插入一个字符,如”thank”=>”thanks”;

- 删除:与插入相反,如”thanks”=>”thank”;

- 替换:替换一个字符,如”Tom”=>”Tim”。

那么编辑距离就是从word1到word2需要几次上述操作。

如果使用动态规划,最重要的就是建立状态转移方程,如果假设dp[i][j]表示一个长为i的字符串和长为j的字符串之间的编辑距离,根据这3个操作可以得出:

- 插入:dp[i][j-1]+1;

- 删除:dp[i-1][j]+1;

- 替换:dp[i-1][j-1]+diff(i,j)

其中,diff指的是word1[i]和word2[j]是否相等,相等则为0,否则为1。

最后只需要取这3种操作中值最小的作为dp[i][j]的值,整个动态规划的运行过程就是填充一张表,,具体代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class Solution {
public:
int minDistance(string word1, string word2) {
const unsigned int m = word1.size();
const unsigned int n = word2.size();

if (m == 0 && n == 0)
return 0;
else if (m == 0)
return n;
else if (n == 0)
return m;

unsigned int i, j;
int E[m + 1][n + 1];

for (i = 0; i <= m; ++i)
E[i][0] = i;

for (j = 1; j <= n; ++j)
E[0][j] = j;

for (i = 1; i <= m; ++i) {
for (j = 1; j <= n; ++j) {
E[i][j] = min(min(E[i - 1][j] + 1, E[i][j - 1] + 1), E[i - 1][j - 1] + (word1[i - 1] != word2[j - 1]));
}
}

return E[m]
;
}
};

int main(int argc, char const *argv[]) {
Solution s;

cout << s.minDistance("XYZ", "SO") << endl;

return 0;
}


可以看到,利用动态规划的思想,我们得到了一种十分高效的算法,时间复杂度为O(mn), 空间复杂度 O(mn)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode dp 动态规划