题目描述:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example
题目思路:
Given word1 = "mart"
and word2 = "karma"
, return 3
.
这题也是dp中的经典问题。用dp[i][j]去表示word1[0...i], word2[0...j]之间的edit distance。那么由于有三种情况,dp方程就是insert, delete, replace方式中cost最小的那个。
Mycode(AC = 25ms):
class Solution {
public:
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
int minDistance(string word1, string word2) {
// write your code here
vector<vector<int>> dp(word1.length() + 1, vector<int>(word2.length() + 1, 0));
// initialize when word2 == " "
for (int i = 0; i <= word1.length(); i++) {
dp[i][0] = i;
}
// initialize when word1 == " "
for (int i = 0; i <= word2.length(); i++) {
dp[0][i] = i;
}
// do dp
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] = min(dp[i][j - 1] + 1, min(dp[i - 1][j - 1], dp[i - 1][j] + 1));
}
else {
dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j - 1], dp[i - 1][j])) + 1;
}
}
}
return dp[word1.length()][word2.length()];
}
};