根据java版本移植
View Code
1 /// <summary> 2 /// 编辑距离算法 3 /// </summary> 4 public class EditDistance 5 { 6 /** 7 * 求三个数中的最小数Mar 1, 2007 8 * 9 * @param a 10 * @param b 11 * @param c 12 * @return 13 */ 14 private static int Minimum(int a, int b, int c) 15 { 16 int mi; 17 18 mi = a; 19 if (b < mi) 20 { 21 mi = b; 22 } 23 if (c < mi) 24 { 25 mi = c; 26 } 27 return mi; 28 } 29 30 /** 31 * 计算两个字符串间的编辑距离Mar 1, 2007 32 * @param s 33 * @param t 34 * @return 35 */ 36 public static int getEditDistance(String s, String t) 37 { 38 int[,] d; // matrix 39 int n = 0; // length of s 40 int m = 0; // length of t 41 int i; // iterates through s 42 int j; // iterates through t 43 char s_i; // ith character of s 44 char t_j; // jth character of t 45 int cost; // cost 46 47 // Step 1 48 49 n = s.Length; 50 m = t.Length; 51 if (n == 0) 52 { 53 return m; 54 } 55 if (m == 0) 56 { 57 return n; 58 } 59 d = new int[n + 1, m + 1]; 60 //d = new int[n+1][+1]; 61 62 // Step 2 63 64 for (i = 0; i <= n; i++) 65 { 66 d[i, 0] = 1; 67 } 68 69 for (j = 0; j <= m; j++) 70 { 71 d[0, j] = j; 72 } 73 74 // Step 3 75 76 for (i = 1; i <= n; i++) 77 { 78 s_i = s[i - 1]; 79 // Step 4 80 for (j = 1; j <= m; j++) 81 { 82 t_j = t[j - 1]; 83 // Step 5 84 if (s_i == t_j) 85 { 86 cost = 0; 87 } 88 else 89 { 90 cost = 1; 91 } 92 // Step 6 93 d[i, j] = Minimum(d[i - 1, j] + 1, d[i, j - 1] + 1, 94 d[i - 1, j - 1] + cost); 95 } 96 } 97 // Step 7 98 return d[n, m]; 99 100 } 101 102 103 }