第十三周:( LeetCode583) Delete Operation for Two Strings(c++)

求字符串编辑距离的题,经典动态规划。

原题:
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: “sea”, “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
Note:
The length of given words won’t exceed 500.
Characters in given words can only be lower-case letters.

思路:
简单的字符串编辑距离变种。由于字符串只能有一种操作(删除)。所以实际上也就是求两个字符串最长相同子串(不要求连续,因为删除操作可以在任意位置)的长度。动态转移方程为:(1)word1[i]=word2[j],dp[i][j]=dp[i-1][j-1]+1(2)word[i]!=word[j],dp[i][j]=max(dp[i-1][j],dp[i][j-1])。时间复杂度为o(n^2)。

代码:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int n1=word1.length(),n2=word2.length();
        int dp[n1+1][n2+1];
        //i,j分别代表word1,word2的第i,j位的字符。i=0,j=0表示字符串为空
        for(int i=0;i<=n1;i++){
            for(int j=0;j<=n2;j++){
                //初始化
                if((i==0)||(j==0))
                    dp[i][j]=0;
                else{
                    if(word1[i-1]==word2[j-1])
                        dp[i][j]=dp[i-1][j-1]+1;
                    else
                        dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return n1+n2-dp[n1][n2]*2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值