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

*Edit Distance

时间:2015-09-25 13:12:34      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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:

  • Insert a character
  • Delete a character
  • Replace a character
Example

Given word1 = "mart" and word2 = "karma", return 3.

技术分享

技术分享
 1 /**
 2  * 本代码由九章算法编辑提供。没有版权欢迎转发。
 3  * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 4  * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
 5  * - 更多详情请见官方网站:http://www.jiuzhang.com/
 6  */
 7 
 8 public class Solution {
 9     public int minDistance(String word1, String word2) {
10         int n = word1.length();
11         int m = word2.length();
12         
13         int[][] dp = new int[n+1][m+1];
14         for(int i=0; i< m+1; i++){
15             dp[0][i] = i; 
16         }
17         for(int i=0; i<n+1; i++){
18             dp[i][0] = i;
19         }
20         
21         
22         for(int i = 1; i<n+1; i++){
23             for(int j=1; j<m+1; j++){
24                 if(word1.charAt(i-1) == word2.charAt(j-1)){
25                     dp[i][j] = dp[i-1][j-1];
26                 }else{
27                     dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]));
28                 }
29             }
30         }
31         return dp[n][m];
32     }
33 }

 

*Edit Distance

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4837713.html

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