计算两个字符串编辑距离
1 public static int levenDistance(String s, String t) { 2 if (s == null || t == null) { 3 return 10; 4 } 5 s = s.toLowerCase(); 6 t = t.toLowerCase(); 7 /* if (Math.abs(s.length() - t.length()) >= 3) { 8 return 3; 9 }*/ 10 int d[][]; // matrix 11 int n; // length of s 12 int m; // length of t 13 int i; // iterates through s 14 int j; // iterates through t 15 char s_i; // ith character of s 16 char t_j; // jth character of t 17 int cost; // cost 18 19 // Step 1 20 n = s.length(); 21 m = t.length(); 22 if (n == 0) { 23 return m; 24 } 25 if (m == 0) { 26 return n; 27 } 28 d = new int[n + 1][m + 1]; 29 30 // Step 2 31 for (i = 0; i <= n; i++) { 32 d[i][0] = i; 33 } 34 35 for (j = 0; j <= m; j++) { 36 d[0][j] = j; 37 } 38 39 // Step 3 40 for (i = 1; i <= n; i++) { 41 42 s_i = s.charAt(i - 1); 43 44 // Step 4 45 for (j = 1; j <= m; j++) { 46 47 t_j = t.charAt(j - 1); 48 49 // Step 5 50 if (s_i == t_j) { 51 cost = 0; 52 } else { 53 cost = 1; 54 } 55 56 // Step 6 57 // d[i][j] = Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, 58 // d[i - 1][j - 1] + cost); 59 // 求三个数的最小值(a<b?a:b)<c?(a<b?a:b):c 60 d[i][j] = ((d[i - 1][j] + 1) < (d[i][j - 1] + 1) ? (d[i - 1][j] + 1) 61 : (d[i][j - 1] + 1)) < (d[i - 1][j - 1] + cost) ? ((d[i - 1][j] + 1) < (d[i][j - 1] + 1) ? (d[i - 1][j] + 1) 62 : (d[i][j - 1] + 1)) 63 : (d[i - 1][j - 1] + cost); 64 65 } 66 67 } 68 69 // Step 7 70 return d[n][m]; 71 72 }