LeetCode Edit Distance DP

来源:互联网 发布:而又何羡乎特殊句式 编辑:程序博客网 时间:2024/06/05 19:31

思路:

方法一:DP。时间复杂度O(N*M),空间复杂度 O(N*M)。

设 f[i][j] 表示 word1[0…i] 与 word2[0…j] 的最小编辑距离,则有:
(1)如果 word1[i] == word2[j],f[i][j] = f[i-1][j-1] ;
(2)如果 word1[i] != word2[j],
如果在word1[i] 后面添加一个字符等于word2[j],则f[i][j] = f[i][j-1] + 1 ;
如果将word1[i]删除,则f[i][j] = f[i-1][j] +1 ;
如果将word1[i]替换为word2[j],则f[i][j] = f[i-1][j-1] + 1 ;

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

方法二:DP+滚动数组。时间复杂度O(N*M),空间复杂度O(N)。

row1: A B
row2: A’ B’

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

要有个变量保存A。

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