zoukankan      html  css  js  c++  java
  • 【Leetcode】72 Edit Distance

    72. Edit Distance

    Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

    You have the following 3 operations permitted on a word:

    a) Insert a character
    b) Delete a character
    c) Replace a character

    Tips: 本题是一道动态规划问题,到当前字符要移动步数的步数,有到前一个字符移动步数决定。

    dp[i][j]表示从word1前i个字符转换到word2前j个字符最少的步骤数。

    从word1转换为Word2,能进行的才操作包括插入、删除、与替换。

    ①插入:dp[i][j]等于包括字符i-1之前的所有字符转换为包括j字符之前的所有字符的步数加一。即

    insert=dp[i-1][j]+1;

    ②删除:dp[i][j]等于包括字符i之前的所有字符转换为包括j-1字符之前的所有字符的步数加一。即

    del=dp[i][j-1]+1;

    ③替换:dp[i][j]等于包括字符i-1之前的所有字符转换为包括j-1字符之前的所有字符的步数加一。即

    change=dp[i-1][j-1]+1;

    dp[i][j]最终的值应为以上三个数值的最小值。

    当 word1与word2遇到一样的字符dp[i][j]=dp[i-1][j-1];

    package hard;
    
    public class L72EditDistance {
    	
    	public int minDistance(String word1, String word2) {
    		//dp二维数组表示从word1的第i个位置转换为word2的第j个位置需要的步数。
    		int len1=word1.length();
    		int len2=word2.length();
    		int[][]dp = new int[len1+1][len2+1];
    		int length=len1>len2?len1:len2;
    		for(int i=0;i<=len1;i++){
    			dp[i][0]=i;
    		}
    		for(int j=0;j<=len2;j++){
    			dp[0][j]=j;
    		}
    		for(int i=1;i<=len1;i++){
    			char ch1=word1.charAt(i-1);
    			for(int j=1;j<=len2;j++){
    				char ch2=word2.charAt(j-1);
    				//当前word1字符等于word2字符,则dp[i][j]=dp[i-1][j-1];
    				if(ch1==ch2){
    					dp[i][j]=dp[i-1][j-1];
    				}else{
    					int insert=dp[i-1][j]+1;
    					int del=dp[i][j-1]+1;
    					int change=dp[i-1][j-1]+1;
    					int min=Math.min(insert,del);
    					min=Math.min(min,change);
    					dp[i][j]=min;
    				}
    				
    			}
    		}
    		return dp[len1][len2];
    	}
    	public static void main(String[] args) {
    		String word1="hello";
    		String word2="hallo";
    		L72EditDistance l72=new L72EditDistance();
    		int count = l72.minDistance(word1, word2);
    		System.out.println(count);
    		
    	}
    
    }
    
  • 相关阅读:
    数据库第1,2,3范式学习
    node.js安装及小例子
    WorkSkill整理之 技能体系
    PTE 准备之 Read aloud
    PTE 准备之 Personal introduction
    PTE准备的时候,用英式英语还是美式英语
    sqlserver2014无法打开报Cannot find one or more components_修复方案
    beego 框架用的页面样式模板
    Go语言开发中MongoDB数据库
    xmind8 破解激活教程
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8370952.html
Copyright © 2011-2022 走看看