Created
March 9, 2017 07:41
-
-
Save deniskyashif/74583231715c646c51c5d9e686ba556a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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