# 最短编辑距离算法实现

①先将 源字符串X 的前 i-1 个字符 X[1...i-1] 转换成 目标字符串Y[1...j]， 然后再 删除字符串X 的第 i 个字符source[i]

②先将 源字符串X[1...j] 转换成 目标字符串Y[1...j-1] ，然后再 插入字符串Y的第 j 个字符 target[j]

③先将 源字符串X[1...i-1] 转换成 目标字符串Y[1...j-1]，然后 源字符串中的 第 i 个字符X[i] 替换为 目标字符串的第 j 个字符 Y[j]

                if (source.charAt(i-1) == target.charAt(j-1)) {
dp[i][j] = dp[i - 1][j - 1];

JAVA实现：

 1 public class MinimumEditDistance {
2
3     public static void main(String[] args) {
4         MinimumEditDistance med = new MinimumEditDistance();
5         String source = "execution";
6         String target = "intention";
7         int result = med.similarDegree(source, target);
8         System.out.println(result);
9     }
10
11     public int similarDegree(String source, String target) {
12         if(source == null || target == null)
13             throw new IllegalArgumentException("illegal input String");
14
15         int sourceLen = source.length();
16         int targetLen = target.length();
17
18         int[][] dp = new int[sourceLen + 1][targetLen +1];
19         //init
20         dp[0][0] = 0;
21         for(int i = 1; i <= sourceLen; i++)
22             dp[i][0] = i;
23         for(int i = 1; i <= targetLen; i++)
24             dp[0][i] = i;
25
26         for(int i = 1; i <= sourceLen; i++) {
27             for(int j = 1; j <= targetLen; j++) {
28                 if (source.charAt(i-1) == target.charAt(j-1)) {
29                     dp[i][j] = dp[i - 1][j - 1];
30                 }else{
31                     int insert = dp[i][j - 1] + 1;//source[0,i] to target[0,j-1] then insert target[j]
32                     int delete = dp[i - 1][j] + 1;//source[0,i-1] to target[0,j] then delete source[i]
33                     int substitute = dp[i - 1][j - 1] + 2;//source[0,i-1] to target[0,j-1] then substitute(source[i] by target[j])
34
35                     int min = min(insert, delete, substitute);
36                     dp[i][j] = min;
37                 }
38             }
39         }
40         return dp[sourceLen][targetLen];
41     }
42
43     private int min(int insert, int delete, int substitute) {
44         int tmp = insert < delete ? insert:delete;
45         int min = tmp < substitute ? tmp:substitute;
46         return min;
47     }
48 }

posted @ 2017-09-02 16:40 hapjin 阅读(...) 评论(...) 编辑 收藏