Edit Distance
2014-01-08 23:28
211 查看
典型的二维动态规划,具体的在这盘文章里讲得很清楚:
http://blog.unieagle.net/2012/09/19/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Aedit-distance%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%8B%E9%97%B4%E7%9A%84%E7%BC%96%E8%BE%91%E8%B7%9D%E7%A6%BB%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/
需要注意的是实现过程中需要格外注意i,j各自代表的意义,以免出错。
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.length() + 1, vector<int>(word2.length() + 1));
for (int i = 0; i <= word1.length(); ++i)
dp[i][0] = i;
for (int j = 0; j <= word2.length(); ++j)
dp[0][j] = j;
for (int i = 1; i <= word1.length(); ++i)
for (int j = 1; j <= word2.length(); ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
continue;
}
dp[i][j] = min(min(dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1), dp[i - 1][j] + 1);
}
return dp[word1.length()][word2.length()];
}
};
http://oj.leetcode.com/problems/edit-distance/
http://blog.unieagle.net/2012/09/19/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Aedit-distance%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%8B%E9%97%B4%E7%9A%84%E7%BC%96%E8%BE%91%E8%B7%9D%E7%A6%BB%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/
需要注意的是实现过程中需要格外注意i,j各自代表的意义,以免出错。
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.length() + 1, vector<int>(word2.length() + 1));
for (int i = 0; i <= word1.length(); ++i)
dp[i][0] = i;
for (int j = 0; j <= word2.length(); ++j)
dp[0][j] = j;
for (int i = 1; i <= word1.length(); ++i)
for (int j = 1; j <= word2.length(); ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
continue;
}
dp[i][j] = min(min(dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1), dp[i - 1][j] + 1);
}
return dp[word1.length()][word2.length()];
}
};
http://oj.leetcode.com/problems/edit-distance/
相关文章推荐
- 1108:棋盘游戏
- 最新报道:广州传智播客PHP培训确定要开班拉
- 关于ios中的文本操作-简介
- 确保当前只有一个窗口进程
- iOS 3D UI---CALayer的transform扩展
- PHP基础封装简单的MysqliHelper类
- [leetcode]Search a 2D Matrix
- c++中的类模板
- 1113:在披萨店里的思考
- 1112:三角形划分区域
- 打开浏览文件夹
- CATransform3DMakeRotation 旋转,翻转
- C#中的委托和事件(续)
- 1109:取石子游戏
- 简单的写日志工具类LogUtil
- 公钥安全机制与宫爆鸡丁的故事
- Java中线程的生命周期
- C#中的委托和事件
- PHP基础Mysql扩展库
- 【py网页】sitecopy代码