Skip to content

Instantly share code, notes, and snippets.

@deniskyashif
Created March 9, 2017 07:41
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 deniskyashif/74583231715c646c51c5d9e686ba556a to your computer and use it in GitHub Desktop.
Save deniskyashif/74583231715c646c51c5d9e686ba556a to your computer and use it in GitHub Desktop.
public static class Distance
{
public static double Levenshtein(string source, string target)
{
if (source.Length == 0)
return target.Length;
if (target.Length == 0)
return source.Length;
if (source == target)
return 0;
var memo = new int[target.Length + 1];
for (int k = 0; k <= target.Length; k++)
memo[k] = k;
for (int i = 1; i <= source.Length; i++)
{
var currentRowMemo = new int[target.Length + 1];
currentRowMemo[0] = i;
for (int k = 1; k <= target.Length; k++)
{
currentRowMemo[k] = Math.Min(
Math.Min(currentRowMemo[k - 1] + 1, memo[k] + 1),
memo[k - 1] + (source[i - 1] != target[k - 1] ? 1 : 0));
}
memo = currentRowMemo;
}
return memo[target.Length];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment