Edit Distance
Problem
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, INT_MAX));
for (int i = 0; i <= n; i++) dp[i][0] = i;
for (int i = 0; i <= m; i++) dp[0][i] = i;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1);
if (word1[j - 1] == word2[i - 1])
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]);
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + 1);
dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1);
}
}
return dp[n][m];
}
};