给定 word1 和 word2 两个单词,找到使 word1 和 word2 相同所需的最少步骤,每个步骤可以删除任一字符串中的一个字符。
样例
样例 1:
输入:"sea", "eat"
输出:2
解释:第 1 步需要将 "sea" 变成 "ea" ,第 2 步 "eat" 变成 ”ea"。
样例 2:
输入:"horse", "ros"
输出:4
解释:需要 3 步使得 "horse" 变成 "os",需要 1 步使得 "ros" 变成 "os"。
注意事项
给出的单词长度不会超过 500。
给出的单词中只包含小写字母。
输入测试数据 (每行一个参数)如何理解测试数据?
class Solution {
public:
/**
* @param word1: a string
* @param word2: a string
* @return: return a integer
*/
map<pair<int,int>, int> mymap;
int minDistance(string &word1, string &word2) {
// write your code here
return dp(word1,word2, word1.size()-1,word2.size()-1);
}
int dp(string &word1, string &word2,int x, int y)
{
if(mymap.count(make_pair(x,y)) != 0)
{
return mymap[make_pair(x,y)];
}
if(x == 0 && y == 0 && word1[x] == word2[y])
return 0;
if(x == 0 && y == 0 && word1[x] != word2[y])
{
return 2;
}
if(x < 0 && y < 0)
return 0;
if(x < 0)
{
return y+1;
}
if(y < 0)
return x+1;
if(word1[x] == word2[y])
{
return dp(word1,word2,x-1,y-1);
}
int time1 = dp(word1,word2,x,y-1);
mymap[make_pair(x,y-1)] = time1;
int time2 = dp(word1,word2,x-1,y);
mymap[make_pair(x-1,y)] = time2;
int ret = min(time1, time2)+1;
mymap[make_pair(x,y)] = ret;
return ret;
}
};