# LeetCode Edit Distance DP

321人阅读 评论(0)

（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];
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
Always Be Coding
Today, I work for myself. Building something new.
个人资料
• 访问：811018次
• 积分：10400
• 等级：
• 排名：第1600名
• 原创：445篇
• 转载：54篇
• 译文：0篇
• 评论：114条
文章分类