Skip to content

Instantly share code, notes, and snippets.

@sanketmaru
Last active August 29, 2015 14:22
Show Gist options
  • Save sanketmaru/0baf23043d04b4221dca to your computer and use it in GitHub Desktop.
Save sanketmaru/0baf23043d04b4221dca to your computer and use it in GitHub Desktop.
levenstein distance
// code has been copied from http://rosettacode.org/wiki/Levenshtein_distance#Java
package main.java;
public class Levenstein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i - 1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String [] args) {
String [] data = { "kitten", "sitting", "saturday", "sunday", "rosettacode", "raisethysword" };
for (int i = 0; i < data.length; i += 2)
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment