[leetcode] 72.Edit Distance

题目:
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
题意:
给定两个字符串,找到字符串A变换到字符串B的最少步骤。
对一个字符串我们有三种操作,第一是插入一个字符,第二是删除一个字符,第三是改变一个字符。
思路:
我们选取A的前i个字符变换到B的前j个字符。如果i==0,那么必须插入j个字符,同理如果j==0的话,那么A字符串删除j个可以使两者变成前j个相等。如果i,j不等于0的话,那么有三种方式,已经知道A的前i-1个字符到j的方法,那么在A中增加一个字符;如果已经知道A的前i-1个字符到达B的方法,那么删除A的第i个字符。如果知道A的前i-1个字符转换到B的前j-1个字符的步骤,那么我们可以通过更换A的第i个字符变成B的第j个字符。如果A的第i个字符跟B的第j个字符相等的话,那么只需要知道A的前i-1个字符变换到B的前j-1个字符的步骤即可。
转移方程是:

  • DP[i][j] = min(DP[i-1][j-1],min(DP[i-1][j],D[i][j-1])) +1
  • if(A[i-1] == B[j-1]) DP[i][j] = min(DP[i][j], DP[i-1][j-1])
    以上。
    代码如下:
class Solution {
public:
    int minDistance(string word1, string word2) {
        if (word1.empty() || word2.empty())return (word1.empty()? word2.length() : word1.length());
        int len1 = word1.length();
        int len2 = word2.length();
        vector<vector<int>> DP(len1 + 1, vector<int>(len2 + 1, 0));
        for (int i = 0; i <= len1; i++)
        for (int j = 0; j <= len2; j++) {
            if (i == 0 || j == 0)DP[i][j] = ((i == 0) ? j : i);
            if (i != 0 && j != 0) {
                DP[i][j] = min(DP[i-1][j-1],min(DP[i - 1][j], DP[i][j - 1])) + 1;
                if(word1[i - 1] == word2[j - 1])DP[i][j] = min(DP[i][j], DP[i - 1][j - 1]);
            }
        }
        return DP[len1][len2];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值