1 20 package hudson.util; 21 22 32 public class EditDistance { 33 34 40 public static int editDistance( String a, String b ) { 41 return new EditDistance(a,b).calc(); 42 } 43 44 50 public static String findNearest( String key, String [] group ) { 51 int c = Integer.MAX_VALUE; 52 String r = null; 53 54 for (String g : group) { 55 int ed = editDistance(key, g); 56 if (c > ed) { 57 c = ed; 58 r = g; 59 } 60 } 61 return r; 62 } 63 64 65 private int[] cost; 66 67 private int[] back; 68 69 70 private final String a,b; 71 72 private EditDistance( String a, String b ) { 73 this.a=a; 74 this.b=b; 75 cost = new int[a.length()+1]; 76 back = new int[a.length()+1]; 78 for( int i=0; i<=a.length(); i++ ) 79 cost[i] = i; 80 } 81 82 85 private void flip() { 86 int[] t = cost; 87 cost = back; 88 back = t; 89 } 90 91 private int min(int a,int b,int c) { 92 return Math.min(a,Math.min(b,c)); 93 } 94 95 private int calc() { 96 for( int j=0; j<b.length(); j++ ) { 97 flip(); 98 cost[0] = j+1; 99 for( int i=0; i<a.length(); i++ ) { 100 int match = (a.charAt(i)==b.charAt(j))?0:1; 101 cost[i+1] = min( back[i]+match, cost[i]+1, back[i+1]+1 ); 102 } 103 } 104 return cost[a.length()]; 105 } 106 } 107 | Popular Tags |