583. Delete Operation for Two Strings

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
class Solution {
public:
    int minDistance(string word1, string word2) {
        unordered_map<string,int>dp;
        return help(word1,word2,dp);
        
    }
private:
    int help(string word1,string word2,unordered_map<string,int>&dp)
    {
        if(dp.find(word1+"#"+word2)!=dp.end()) return dp[word1+"#"+word2];
        int res = INT_MAX;
        if(word1.size()==0 || word2.size()==0)
        {
            res= word1.size()>0?word1.size():word2.size();
        }
        else
        {
        if(word1[0]!=word2[0])
           res= 1+min(help(word1.substr(1),word2,dp),help(word1,word2.substr(1),dp));
        else
            res= help(word1.substr(1),word2.substr(1),dp);
        }
        dp[word1+"#"+word2] = res;
        return res;
    }
};

 还有一种动态规划解法,

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        vector<vector<int>>dp(m+1,vector<int>(n+1));
        //边界条件需要考虑
        for(int i=1;i<=m;i++) dp[i][0]=i;
        for(int j=1;j<=n;j++) dp[0][j]=j;
        
        for(int i = 1;i<=m;i++)
            for(int j = 1;j<=n;j++)
                if(word1[i-1]==word2[j-1]) dp[i][j]= dp[i-1][j-1];
                else dp[i][j] = 1 + min(dp[i-1][j],dp[i][j-1]);
        return dp[m][n];
    }
};

 

posted @ 2017-12-26 02:13  jxr041100  阅读(111)  评论(0编辑  收藏  举报