zoukankan      html  css  js  c++  java
  • leetcode 72. 编辑距离

    题意

    给定两个单词 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')

    思路

    这是一道动态规划问题,与leetcode第十题 正则表达式匹配 很相似,也比第十题简单很多。

    每当拿到一个道动态规划问题,我们首先要定义状态状态转移方程。这道题我们定义$dp[i][j]$表示word1从前i个字符组成的字符串转换成word2从前j个字符组成的字符串所使用的最小操作次数。接下来就是要考虑状态转移问题,很明显题目中讲述了总共有3种操作,状态转移方程为

    $dp[i][j]=min(dp[i-1][j-1]+flag,dp[i-1][j],dp[i][j-1]+1),其中word1[i]=word2[j]时flag=1,其它为0$

    • $dp[i-1][j-1]+flag$表示替换字符,如果这2个字符恰好相等,即flag为0不用替换
    • $dp[i-1][j]+1$表示删除字符,即word1的前i-1个字符已经转换成word2的前j个字符了,当word1还有第i个字符时,我们可以将这个字符删除,同时增加一次操作
    • $dp[i][j-1]+1$表示增加字符,即word1的前i个字符已经转换成word2的前j-1个字符了,当word2还有第个j字符时,我们可以在word1的后面增加这个j字符,同时增加一次操作

     

    代码

    class Solution {
    public:
        int minDistance(string word1, string word2) {
           int dp[1000][1000];
            int n = word1.length();
            int m = word2.length();
            dp[0][0] = 0;
            for(int i=0;i<word1.length();i++)
            {
                dp[i+1][0] = i+1;
            }
            for(int j=0;j<word2.length();j++)
            {
                dp[0][j+1] = j+1;
            }
            for(int i=0;i<word1.length();i++)
            {
                for(int j=0;j<word2.length();j++)
                {
                    int flag = 1;
                    if(word1[i]==word2[j])
                    {
                        flag = 0;
                    }
                    dp[i+1][j+1] = min(dp[i][j]+flag,min(dp[i][j+1]+1,dp[i+1][j]+1));
                }
            } 
            return dp[n][m];
        }
    };
  • 相关阅读:
    You are not late! You are not early!
    在同一个服务器(同一个IP)为不同域名绑定的免费SSL证书
    Vue.js Is Good, but Is It Better Than Angular or React?
    It was not possible to find any compatible framework version
    VS增加插件 Supercharger破解教程
    Git使用ssh key
    Disconnected: No supported authentication methods available (server sent: publickey)
    VS 2013打开.edmx文件时报类型转换异常
    asp.net MVC4 框架揭秘 读书笔记系列3
    asp.net MVC4 框架揭秘 读书笔记系列2
  • 原文地址:https://www.cnblogs.com/simplekinght/p/12068977.html
Copyright © 2011-2022 走看看