Skip to content

Instantly share code, notes, and snippets.

@mdamien
Last active August 29, 2015 14:19
Show Gist options
  • Save mdamien/1c6f7c8888a271caadc9 to your computer and use it in GitHub Desktop.
Save mdamien/1c6f7c8888a271caadc9 to your computer and use it in GitHub Desktop.
Levenshtein java
public static char NULL = '\u0000';
public static int cout(char x, char y){
if(x == NULL){ //insertion
return 1;
}
if(y == NULL){ //insertion
return 1;
}
if(x != y){ //substitution
return 1;
}
return 0;
}
public static int distance(String a, String b){
int[][] dist = new int[a.length()+1][b.length()+1];
char X,Y;
int d1,d2,d3;
for(int i = 1;i <= a.length();i++){
X = a.charAt(i-1);
dist[i][0] = dist[i-1][0] + cout(X,NULL);
}
for(int j = 1;j <= b.length();j++){
Y = b.charAt(j-1);
dist[0][j] = dist[0][j] + cout(NULL,Y);
}
for(int i = 1;i <= a.length();i++){
X = a.charAt(i-1);
for(int j = 1;j <= b.length();j++){
Y = b.charAt(j-1);
d1 = dist[i-1][j-1] + cout(X,Y);
d2 = dist[i-1][j] + cout(X,NULL);
d3 = dist[i][j-1] + cout(NULL,Y);
dist[i][j] = Math.min(d1, Math.min(d2,d3));
}
}
return dist[a.length()][b.length()];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment