题目
给定两个字符串word1, word2。求出从word1到word2步骤最少的修改方式,修改方式包括替换(replace),插入(insert),删除(delete)。
- replace: “replace” -> “eeplace”
- insert: “insert” -> “iinsert”
- delete: “delete” ->”elete”
解法
我们使用一个二维数组dp来记录从word1到word2的修改步骤,dp[i][j]对应的是从word1[0…i]到word[0…j]
Boundary
从空字符串转换到任意字符串和从任意字符串抓换到空串的操作次数都为改任意字符串的长度(n次插入或n次删除)
dp[i][0] = i;
dp[0][j] = j;
Regular
我们使用一个二维数组dp来记录从word1到word2的修改步骤,dp[i][j]对应的是从word1[0…i]到word[0…j],对应每一种修改方式我们都有不同的状态转移方程
- replace: dp[i – 1][j – 1] + 1 //保留从word1[0 … i-1]转变到word2[0 … j-1]的次数,再加一,加一指的是本次的修改
- insert: dp[i][j – 1] + 1 // 保留从word1[0 … i]转变到word2[0 … j-1]的次数,加一
- delete: dp[i – 1][j] + 1// 保留从word1[0 … i-1]转变到word2[0 … j]的次数,加一
对于替换替换还是删除,我们选其中最小的值
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int size1 = word1.size(), size2 = word2.size();
vector<vector<int>> dp(size1 + 1, vector<int>(size2 + 1, 0));
for (int i = 0; i <= size1; i++) dp[i][0] = i;
for (int j = 0; j <= size2; j++) dp[0][j] = j;
for (int i = 1; i <= size1; i++) {
for (int j = 1; j <= size2; j++) {
int replace = word1[i - 1] == word2[j - 1] ? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1;
// insert: dp[i][j - 1], which means we use the steps from word1[0..i] to word[0..j]
// delete: dp[i - 1][j], same as the previous one
// and dont forget + 1;
int ins_del = min(dp[i][j - 1], dp[i - 1][j]) + 1;
dp[i][j] = min(replace, ins_del);
}
}
return dp.back().back();
}
};
TODO: Reduce space complexity