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

Leetcode: Edit Distance

时间:2014-10-08 07:40:24      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

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

典型DP,很难想,知道方法后就很容易实现了

这道题叫Edit Distance,因为Edit Distance定义就是:Given two string S1, S2, the minimum number of operations to convert one into another.

https://www.youtube.com/watch?v=CB425OsE4Fo&list=PL0174E49C0E0DD5C8&index=35这个视频讲的很好,关注20:00, 31:54, 34:32等处

bubuko.com,布布扣

res[i][j]表示Edit Distance between X数组的前i个元素以及Y数组的前j个元素,或者the minimum # of operations to convert X前i个元素 into Y的前j个元素

因为对于Xi 和 Yj,操作无非是 insert, delete, replace三种,所以递归式就是三项:根据上面这个图很清楚:res[i][j] = min{res[i-1][j]+1, res[i][j-1]+1, Xi == Yj ? res[i-1][j-1] : res[i-1][j-1] + 1}

 1 public class Solution {
 2     public int minDistance(String word1, String word2) {
 3         if (word1==null && word2!=null) return word2.length();
 4         if (word1!=null && word2==null) return word1.length();
 5         if (word1==null && word2==null) return 0;
 6         int[][] res = new int[word1.length()+1][word2.length()+1];
 7         for (int i=1; i<=word1.length(); i++) {
 8             res[i][0] = i;
 9         }
10         for (int j=1; j<=word2.length(); j++) {
11             res[0][j] = j;
12         }
13         for (int m=1; m<=word1.length(); m++) {
14             for (int n=1; n<=word2.length(); n++) {
15                 res[m][n] = Math.min(Math.min(res[m-1][n]+1, res[m][n-1]+1), word1.charAt(m-1)==word2.charAt(n-1)? res[m-1][n-1] : res[m-1][n-1]+1);
16             }
17         }
18         return res[word1.length()][word2.length()];
19     }
20 }

 

Leetcode: Edit Distance

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/EdwardLiu/p/4010380.html

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