您的位置:首页 > 其它

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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: