Edit Distance

来源:互联网 发布:小说人物起名软件 编辑:程序博客网 时间:2024/03/29 09:48

典型的二维动态规划,具体的在这盘文章里讲得很清楚:

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/

0 0
原创粉丝点击