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

leetcode------Edit Distance

时间:2015-03-08 20:08:42      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

标题: Edit Distance
通过率: 26.1%
难度:

 

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

本题是动态规划的经典题目,公式如下:

1、s1.length==0,return s2.length;

2、s2.length==0,return s1.length;

3、if  s1.charat(i)==s2.charat(j),res[i][j]=res[i-1][j-1]

  else  res[i][j]=min(res[i-1][j],res[i][j-1],res[i-1][i-1]+1)

具体看代码:

 1 public class Solution {
 2     public int minDistance(String word1, String word2) {
 3 int len1 = word1.length();
 4     int len2 = word2.length();
 5  
 6     // len1+1, len2+1, because finally return dp[len1][len2]
 7     int[][] dp = new int[len1 + 1][len2 + 1];
 8  
 9     for (int i = 0; i <= len1; i++) 
10         dp[i][0] = i;
11     
12     for (int j = 0; j <= len2; j++) 
13         dp[0][j] = j;
14     
15  
16     //iterate though, and check last char
17     for (int i = 1; i <= len1; i++) {
18         char c1 = word1.charAt(i-1);
19         for (int j = 1; j <= len2; j++) {
20             char c2 = word2.charAt(j-1);
21  
22             //if last two chars equal
23             if (c1 == c2) {
24                 //update dp value for +1 length
25                 dp[i][j] = dp[i-1][j-1];
26             } else {
27                 int replace = dp[i-1][j-1] + 1;
28                 int insert = dp[i-1][j] + 1;
29                 int delete = dp[i][j-1] + 1;
30  
31                 int min = Math.min(replace, insert);
32                 min = Math.min(min,delete);
33                 dp[i][j] = min;
34             }
35         }
36     }
37  
38     return dp[len1][len2];
39     }
40 }

 

 

     

leetcode------Edit Distance

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4322147.html

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