zoukankan      html  css  js  c++  java
  • 72. Edit Distance

    Description

    Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
    
    You have the following three operations permitted on a word:
    
              Insert a character
              Delete a character
              Replace a character
    

    Example

    Input: word1 = "horse", word2 = "ros"
    Output: 3
    Explanation: 
    horse -> rorse (replace 'h' with 'r')
    rorse -> rose (remove 'r')
    rose -> ros (remove 'e')
    

    Tips

    0 <= word1.length, word2.length <= 500
    word1 and word2 consist of lowercase English letters.
    

    分析

    简单的 dp 题目
    
        def minDistance(self, word1, word2):
            """
            :type word1: str
            :type word2: str
            :rtype: int
            """
            N, M = len(word1), len(word2)
            dp = [[N+M+2 for j in range(M+1)]  for i in range(1+N)]
      
            dp[0][0] 
       
            for i in range(1, N+1):
                for j in range(1, M+1):
                    d = 1
                    if word1[i-1] == word2[j-1]:
                        d = 0
                    dp[i][j] = min(dp[i-1][j-1] +d , dp[i][j-1] + 1, dp[i-1][j] + 1)
    
            return dp[-1][-1]
    计算结果总是出错,主要是初始化出错了!! 没有初始化 dp[0][j] 和 dp[i][0] 
    
    
  • 相关阅读:
    C#类型转换
    C#运算符
    SQL视图与触发器
    存储过程
    SQL 变量
    SQL 经典练习题
    字符串函数,数据类型转换,链接查询,纵向查询
    常用的 SQL 函数
    习题整理(1)
    子查询的部分内容
  • 原文地址:https://www.cnblogs.com/tmortred/p/15763688.html
Copyright © 2011-2022 走看看