编辑距离

Leetcode72题

给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符
删除一个字符
替换一个字符

示例 1:

输入: word1 = "horse", word2 = "ros"
输出: 3
解释: 
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:

输入: word1 = "intention", word2 = "execution"
输出: 5
解释: 
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')
解题思路:
1、word1[0:i-1]  - k步 -> word2[0:j-1]
if(word1[i] == word2[j]) -> k步
else -> k+1步

2、word1[0:i] - k步 -> word2[0:j-1]
word1[0:i] - k+1步 -> word2[0:j]

3、word1[0:i-1] - k步 -> word2[0:j]
word1[0:i] - k+1步 -> word2[0:j]

解题:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.size(), len2 = word2.size();
        if(len1 == 0 && len2 == 0) return 0;
        if(len1 == 0 || len2 == 0) return (len1 > len2 ? len1 : len2);
        // 初始化dp
        int **dp;
        dp = new int*[len2 + 1];
        for(int i = 0; i < len2 + 1; ++i) {
            dp[i] = new int[len1 + 1];
        }
        // 处理边界
        dp[0][0] = 0;
        for(int i = 1; i < len1 + 1; ++i) {
            dp[0][i] = i;
        }
        for(int i = 1; i < len2 + 1; ++i) {
            dp[i][0] = i;
        }
        for(int i = 1; i < len2 + 1; ++i) {
            for(int j = 1; j < len1 + 1; ++j) {
                // (1) word1[0 : n-1] --> word2[0 : n-1] = k;
                int step1 = dp[i - 1][j - 1];
                if(word1[j - 1] != word2[i - 1])
                    ++step1;
                
                // (2) word1[0 : n-1] --> word2[0 : n] = k
                int step2 = dp[i][j - 1] + 1;
                
                // (3) word1[0 : n] --> word2[0 : n-1] = k
                int step3 = dp[i - 1][j] + 1;
                
                dp[i][j] = min(min(step1, step2), step3);
            }
        }
        return dp[len2][len1];
    }
};

你可能感兴趣的:(编辑距离)