Skip to content

Instantly share code, notes, and snippets.

@mikaelnet
Created April 17, 2015 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelnet/f1d63e2beb197554743d to your computer and use it in GitHub Desktop.
Save mikaelnet/f1d63e2beb197554743d to your computer and use it in GitHub Desktop.
Computes Levenshtein Distance of two strings
public static class LevenshteinDistanceComputer
{
public static int LevenshteinDistance(this string s, string t)
{
return Compute(s, t);
}
public static int Compute(string s, string t)
{
if (string.IsNullOrEmpty(s))
{
if (string.IsNullOrEmpty(t))
return 0;
return t.Length;
}
if (string.IsNullOrEmpty(t))
{
return s.Length;
}
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// initialize the top and right of the table to 0, 1, 2, ...
for (int i = 0; i <= n; d[i, 0] = i++) ;
for (int j = 1; j <= m; d[0, j] = j++) ;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
int min1 = d[i - 1, j] + 1;
int min2 = d[i, j - 1] + 1;
int min3 = d[i - 1, j - 1] + cost;
d[i, j] = Math.Min(Math.Min(min1, min2), min3);
}
}
return d[n, m];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment