Leetcode动态规划之PHP解析(72. Edit Distance)

栏目: 编程工具 · 发布时间: 5年前

内容简介:动态规划题系列最后一题

2 0 1 9 -5 -26   期天    

这周四周五有事情没有更新

动态规划题系列最后一题

Leetcode动态规划之 <a href='https://www.codercto.com/topics/18749.html'>PHP</a> 解析(72. Edit Distance)

题目描述

给定两个字符串暂且称之为a,b,让我们求把字符串a变成字符串b至少需要几步操作,操作的动作分别是delete,insert,replace,并且每个操作只能操作一个字符串。

题目解析

还是那两个步骤,状态的定义以及递推公式。分两种情况,如果他们相等,当前的替换数就等于之前的替换数,否则直接比较前增,删,改的替换数最小值作为当前最小替换数。           

Leetcode动态规划之PHP解析(72. Edit Distance)

/**
     * @param String $word1
     * @param String $word2
     * @return Integer
     */
    function minDistance($word1, $word2) {
    
        for($i=0;$i<=strlen($word1);$i++) $dp[$i][0]=$i;
        for($i=0;$i<=strlen($word2);$i++) $dp[0][$i]=$i;      
        
        for($i=1;$i<=strlen($word1);$i++){
            for($j=1;$j<=strlen($word2);$j++){
                if(substr($word1,$i-1,1)==substr($word2,$j-1,1)){
                    $dp[$i][$j]=$dp[$i-1][$j-1];
                }else{
                    $dp[$i][$j]=min($dp[$i-1][$j],$dp[$i][$j-1],$dp[$i-1][$j-1])+1;
                }
            }
        }
        return $dp[strlen($word1)][strlen($word2)];
    }

Github整理地址: https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Types and Programming Languages

Types and Programming Languages

Benjamin C. Pierce / The MIT Press / 2002-2-1 / USD 95.00

A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors by classifying program phrases according to the kinds of values they compute. The study of typ......一起来看看 《Types and Programming Languages》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具