###### LeetCode Edit Distance DP

（1）如果 word1[i] == word2[j]，f[i][j] = f[i-1][j-1] ;
（2）如果 word1[i] != word2[j]，

c++:

class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size();
int n2 = word2.size();
vector<vector<int>> f = vector<vector<int>>(n1 + 1, vector<int>(n2 + 1, 0));
for(int i = 0; i <= n1; ++i) {
f[i][0] = i;
}
for(int i = 0; i <= n2; ++i) {
f[0][i] = i;
}
for(int i = 1; i <= n1; ++i) {
for(int j = 1; j <= n2; ++j) {
if(word1[i - 1] == word2[j - 1]) {
f[i][j] = f[i-1][j-1];
}else {
int tmp = min(f[i][j-1] + 1, f[i-1][j] + 1);
f[i][j] = min(tmp, f[i-1][j-1] + 1);
}
}
}
return f[n1][n2];
}
};

java:

public class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();

int[][] cost = new int[m + 1][n + 1];
for(int i = 0; i <= m; ++i) {
cost[i][0] = i;
}
for(int i = 0; i <= n; ++i) {
cost[0][i] = i;
}

for(int i = 1; i <= m; ++i) {
for(int j = 1; j <= n; ++j) {
if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
cost[i][j] = cost[i - 1][j - 1];
}else {
int tmp = cost[i - 1][j] + 1 < cost[i][j - 1] + 1 ? cost[i - 1][j] + 1 : cost[i][j - 1] + 1;
cost[i][j] = tmp < cost[i - 1][j - 1] + 1 ? tmp : cost[i - 1][j - 1] + 1;
}
}
}

return cost[m][n];
}
}

row1: A B
row2: A’ B’

B’ = min(A, A’, B);

class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size();
int m = word2.size();
if(n < m) {
minDistance(word2, word1);
}

vector<int> f = vector<int>(m + 1, 0);
for(int i = 0; i <= m; ++i) {
f[i] = i;
}

for(int i = 1; i <= n; ++i) {
int upper_left = f[0];
f[0] = i;
for(int j = 1; j <= m; ++j) {
int upper = f[j];
if(word1[i-1] == word2[j-1]) {
f[j] = upper_left;
}else {
f[j] = 1 + min(upper_left, min(f[j], f[j-1]));
}
upper_left = upper;
}
}
return f[m];
}
};

#### LeetCode-72. Edit Distance (JAVA)字符串最小编辑距离DP&DFS

2017-04-27 11:08:09

#### LeetCode(72)Edit Distance

2013-12-23 13:27:56

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

2014-06-18 15:27:43

#### LeetCode 72 — Edit Distance（C++ Python）

2014-07-31 22:24:13

#### LeetCode72——Edit Distance

2015-11-14 14:07:54

#### Edit Distance -- LeetCode

2014-04-21 01:43:21

#### leetcode 161: One Edit Distance

2015-01-02 13:41:19

#### leetCode 72.Edit Distance (编辑距离) 解题思路和方法

2015-07-17 16:58:01

#### LeetCode Edit Distance 终极省内存方法

2013-12-22 08:13:57

#### leetcode_c++：Edit Distance (072)

2016-08-14 15:45:57

## 不良信息举报

LeetCode Edit Distance DP