72.编辑距离

参考:
https://leetcode.com/problems/edit-distance/discuss/25846/C%2B%2B-O(n)-space-DP

dp[i][j]表示将s1[0..i)变成s2[0..j)最少的步骤数,
s1[0..i)变成s2[0..j)可以考虑以下三种情况:

1. 如果s1[i-1]==s2[j-1],即两者的最后一位字符相同,那么只需要将s1[0..i-1)变成s2[0..j-1),最后一个就不用变了,因此dp[i][j]=dp[i-1][j-1]

2. 如果s1[i-1]=s2[j-1],那么有三种方法进行变换:
  (1)将s1[0..i-1)变成s2[0..j-1),最后一个采用替换的方法,因此dp[i][j]=dp[i-1][j-1]+12)将s1[0..i-1)变成s2[0..j),然后将s1[i-1]删除,因此dp[i][j]=dp[i-1][j]+13)将s1[0..i)变成s2[0..j-1),然后给s1[i-1]后面插入一个s2[j-1],因此dp[i][j]=dp[i][j-1]+1
  最终取三个的最小值
class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); //行和列分别比字符长多一
        for (int i = 1; i <= m; i++) { //初始化行,从1开始的,(0,0)位置为0
            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 { //最后一个不等,从上,左,左上里取最小值+1
                    dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
                }
            }
        }
        return dp[m][n];
    }
};

还可以优化空间复杂度
用两个数组(未看)

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        vector<int> pre(n + 1, 0), cur(n + 1, 0);
        for (int j = 1; j <= n; j++) {
            pre[j] = j;
        }
        for (int i = 1; i <= m; i++) {
            cur[0] = i;
            for (int j = 1; j <= n; j++) {
                if (word1[i - 1] == word2[j - 1]) {
                    cur[j] = pre[j - 1];
                } else {
                    cur[j] = min(pre[j - 1], min(cur[j - 1], pre[j])) + 1;
                }
            }
            fill(pre.begin(), pre.end(), 0);
            swap(pre, cur);
        }
        return pre[n];
    }
};

用一个数组(未看)

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size(), pre;
        vector<int> cur(n + 1, 0);
        for (int j = 1; j <= n; j++) {
            cur[j] = j;
        }
        for (int i = 1; i <= m; i++) {
            pre = cur[0];
            cur[0] = i;
            for (int j = 1; j <= n; j++) {
                int temp = cur[j];
                if (word1[i - 1] == word2[j - 1]) {
                    cur[j] = pre;
                } else {
                    cur[j] = min(pre, min(cur[j - 1], cur[j])) + 1;
                }
                pre = temp;
            }
        }
        return cur[n];
    }
};

你可能感兴趣的:(leetcode)