首页 > 代码库 > Leetcode: Edit Distance

Leetcode: 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 characterb) Delete a characterc) 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等处

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