本题要求删除两个单词中的字母使得剩余字母均相同,因此设置dp数组,dp[i][j]的含义是0-(i-1)个字母和0-(j-1)个字母相同时需要删除的最少次数。递推公式在word1[i-1]=word2[j-1]时,dp[i][j]=dp[i-1][j-1], 不相同时dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1])。
具体代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>>dp(word1.length()+1,vector<int>(word2.length()+1,0));
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];
}
else
{
dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1);
}
}
}
return dp[word1.length()][word2.length()];
}
};
二、leetcode第72题
本题要求对两个单词操作使得两个单词剩余字母相等,与上题不同之处在于操作包括增添、删除和替换三种,因此在word1[i-1]!=word2[j-1]时递推式变为dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1),也就是加上了替换的操作。
具体代码如下:
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];
}
else
{
dp[i][j]=min(dp[i][j-1]+1,min(dp[i-1][j]+1,dp[i-1][j-1]+1));
}
}
}
return dp[word1.length()][word2.length()];
}
};