码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode72 Edit Distance

时间:2018-01-28 13:49:08      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:public   style   convert   replace   lap   动态规划   移动   tco   mit   

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);
		
	}

}

 

Leetcode72 Edit Distance

标签:public   style   convert   replace   lap   动态规划   移动   tco   mit   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8370952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!