# Edit Distance

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:

a) Insert a character
b) Delete a character
c) Replace a character

1. Replace word1[i - 1] by word2[j - 1] (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement));
2. Delete word1[i - 1] and word1[0..i - 2] = word2[0..j - 1] (dp[i][j] = dp[i - 1][j] + 1 (for deletion));
3. Insert word2[j - 1] to word1[0..i - 1] and word1[0..i - 1] + word2[j - 1] = word2[0..j - 1] (dp[i][j] = dp[i][j - 1] + 1 (for insertion)).

int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<vector<int> > dp(m + 1, vector<int> (n + 1, 0));
for (int i = 1; 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] + 1, min(dp[i][j - 1] + 1, dp[i - 1][j] + 1));
}
}
return dp[m][n];
}

#### edit distance 理解

2014-01-07 04:43:56

#### Edit Distance (Java)

2015-01-29 11:15:44

#### 通过Edit Distance问题理解动态规划算法

2015-03-25 21:24:47

#### 动态规划 求解 Minimum Edit Distance

2012-07-11 12:17:41

#### LeetCode(72)Edit Distance

2013-12-23 13:27:56

#### lintcode: Edit Distance

2016-04-11 15:56:34

#### LeetCode 72 Edit Distance(Python详解及实现)

2017-08-05 16:17:05

#### LeetCode-Edit Distance 编辑距离与动态规划

2014-06-18 15:27:43

#### Edit Distance相似度算法

2015-12-08 12:47:23

#### leetcode 161: One Edit Distance

2015-01-02 13:41:19