leetcode #72 in cpp

Solution:

We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]

Code:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));//dp[i][j]-->min step convert word1[0..i-1] to word2[0...j-1]
        dp[0][0] = 0;
        for(int i = 1; i < len2+1; i ++){
            dp[0][i] = i;
        }
        for(int i = 1; i< len1 + 1; i ++){
            dp[i][0] = i;
        }
        
        for(int i = 1; i < len1+1; i++){
            for(int j = 1; j < len2 + 1; j ++){
                if(word1[i-1] == word2[j-1]){
                    dp[i][j] = dp[i-1][j-1];
                }else{
                    //delete word1[i-1] and make word1[0...i-2] to word2[0..j-1], or replace word1[i-1] with word2[j-1]
                    int mini = min(dp[i-1][j], dp[i-1][j-1]);
                                    //make word1[0...i-1] to word2[0...j-2], insert word2[j-1] into word1
                    mini = min(mini, dp[i][j-1]);
                    dp[i][j] = mini + 1;
                }
            }
        }
        return dp[len1][len2];
    }
};


阅读更多
文章标签: cpp leetcode
个人分类: interview
上一篇leetcode #71 in cpp
下一篇leetcode #73 in cpp
想对作者说点什么? 我来说一句

LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

没有更多推荐了,返回首页

关闭
关闭