zoukankan      html  css  js  c++  java
  • leetcode 编辑距离(动态规划)

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

    题解:编辑距离是典型的动态规划问题。

    首先,我们考虑对于s1的每一个字符,有四种选择,什么都不做,替换,删除,添加;

    假设dp[i][j]表示第一个字符串的前i个字符和s2的前j个字符变成相同所需要的最少操作次数。

    if(s1[i]==s2[j]) dp[i][j]=dp[i-1][j-1];

    else

      dp[i][j]=min{

            dp[i-1][j],  // 把s1的第i个字符删除

            dp[i][j-1],  //在s1中插入一个字符

            dp[i-1][j-1],吧s1的第i字符替换

      };

    参考代码:

     1 class Solution {
     2 public:
     3     int minDistance(string word1, string word2) 
     4     {
     5         int n=word1.length(),m=word2.length();
     6         if(n==0) return m;
     7         if(m==0) return n;
     8         int dp[n+1][m+1]={0};
     9         for(int i=1;i<=n;++i) dp[i][0]=i;
    10         for(int j=1;j<=m;++j) dp[0][j]=j;
    11 
    12         for(int i=1;i<=n;++i)
    13             for(int j=1;j<=m;++j)
    14             {
    15                 if(word1[i-1]==word2[j-1])
    16                     dp[i][j]=dp[i-1][j-1];
    17                 else
    18                     dp[i][j]=min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+1));
    19             } 
    20         return dp[n][m];
    21     }
    22 };
    C++
  • 相关阅读:
    A1023 Have Fun with Numbers [大整数乘法]
    大整数的四则运算
    A1096 Consecutive Factors [因子分解]
    A1078 Hashing [质数和散列结合]
    A1015 Reversible Primes [质数问题]
    又谈进制转换
    A1088 Rational Arithmetic [分数四则运算]
    A1081 Rational Sum [分数计算]
    linux主流系统配置静态ip
    主机ping虚拟机请求超时,虚拟机ping主机正常ping通导致ssh连接问题
  • 原文地址:https://www.cnblogs.com/csushl/p/12364459.html
Copyright © 2011-2022 走看看