题目描述
给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同所需的最小步数。
每步 可以删除任意一个字符串中的一个字符。
代码
解法1
/*dp[i][j]:以i-1为结尾的wrod1中有以j-1为尾的word2的个数为了让word1和word2相同,最少操作次数为dp[i][j]递推公式:当word1[i - 1] 与 word2[j - 1]相同的时候,dp[i][j] = dp[i - 1][j - 1]; 当word1[i - 1] 与 word2[j - 1]不相同的时候,有三种情况:情况一:删word1[i - 1],最少操作次数为dp[i - 1][j] + 1情况二:删word2[j - 1],最少操作次数为dp[i][j - 1] + 1情况三:同时删word1[i - 1]和word2[j - 1],操作的最少次数为dp[i - 1][j - 1] + 2因为 dp[i][j - 1] + 1 = dp[i - 1][j - 1] + 2,所以递推公式可简化为:dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);初始化:dp[i][0] = i, 表示word1不为空,word2为空,需要删除i个元素dp[0][j] = j, 表示word1为空,word2不为空,需要删除j个元素递推公式for(int i=1;i<=word1.size();i++)for(int j=1;j<=word2.size();j++)*/
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, 0));for (int i = 0; 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] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);}}return dp[m][n];}
};
解法2:利用最长公共子序列
/*使用最长公共子序列:求出最长公共子序列,然后使用两个字符串分别减去公共就可计算出每个字符串删除的元素return (word1.size()-dp[m][n]) + (word2.size()-dp[m][n])
*/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, 0));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] + 1;else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);}}return (m - dp[m][n]) + (n - dp[m][n]);}
};