LeetCode题解–72. Edit Distance

链接

LeetCode题目:https://leetcode.com/problems/edit-distance/

难度:Hard

题目

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
题目大意是算出一个字符串转变为另一个字符串所需的最小步骤,其中增、删、替换一个字符各算一个步骤。

分析

涉及最优子结构问题可以使用动态规划算法。定义minDis[i][j]为word1前i个字符转变为word2前j个字符所需的最小步骤数,初始化minDis[i][0]=i,minDis[0][i]=i。
当word1的第i个字符和word2的第j个字符不相等时,考虑三种情况,第一种是word1前i-1个字符转变为word2前j-1个字符,然后word1第i个字符替换为word2第j个字符;第二种是word1前i-1个字符转变为word2前j个字符,然后删掉word1第i个字符;第三种是word1前i个字符转变为word2前j-1个字符,然后增加word2第j个字符。
而当word1的第i个字符和word2的第j个字符相等时,只需要考虑word1前i-1个字符转变为word2前j-1个字符的最小步骤。

代码

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = (int) word1.size(), len2 = (int) word2.size();
        vector<vector<int>> minDis;
        for (int i = 0; i <= len1; i++) {
            vector<int> temp;
            for (int j = 0; j <= len2; j++) {
                temp.push_back(0);
            }
            minDis.push_back(temp);
        }
        for (int i = 1; i <= len1; i++) {
            minDis[i][0] = i;
        }
        for (int i = 1; i <= len2; i++) {
            minDis[0][i] = i;
        }
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1[i - 1] != word2[j - 1]) {
                    minDis[i][j] = min(min(minDis[i - 1][j - 1], minDis[i - 1][j]),
                                       minDis[i][j - 1]) + 1;
                } else {
                    minDis[i][j] = minDis[i - 1][j - 1];
                }
            }
        }
        return minDis[len1][len2];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值