• Source
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5.  
    6. namespace SEA2016.FuzzySearch
    7. {
    8. /// <summary>
    9. /// Calculate Levenshtein distance between two strings using brute-force recursive algorithm
    10. /// https://en.wikipedia.org/wiki/Levenshtein_distance#Recursive
    11. /// </summary>
    12. public static class LevenshteinBruteForce
    13. {
    14. public static int Calculate(string a, string b)
    15. {
    16. return CalculateRecursive(a, b, a.Length, b.Length);
    17. }
    18.  
    19. private static int CalculateRecursive(string a, string b, int m, int n)
    20. {
    21. if (Math.Min(m, n) == 0)
    22. {
    23. return Math.Max(m, n);
    24. }
    25.  
    26. var subCost = ((a[m - 1] == b[n - 1]) ? 0 : 1) + CalculateRecursive(a, b, m - 1, n - 1);
    27. var delCost = 1 + CalculateRecursive(a, b, m, n - 1);
    28. var insCost = 1 + CalculateRecursive(a, b, m - 1, n);
    29.  
    30. return Math.Min(subCost, Math.Min(insCost, delCost));
    31. }
    32.  
    33. private static int Calculate2(string a, string b, int m, int n)
    34. {
    35. if (b.Length == n)
    36. {
    37. return (a.Length - m);
    38. }
    39.  
    40. if (a.Length == m)
    41. {
    42. return (b.Length - n);
    43. }
    44.  
    45. if (a[m] == b[n])
    46. {
    47. return Calculate2(a, b, m + 1, n + 1);
    48. }
    49. else
    50. {
    51. var subCost = Calculate2(a, b, m + 1, n + 1);
    52. var delCost = Calculate2(a, b, m + 1, n);
    53. var insCost = Calculate2(a, b, m, n + 1);
    54.  
    55. return 1 + Math.Min(subCost, Math.Min(insCost, delCost));
    56. }
    57. }
    58. }
    59.  
    60.  
    61. public static class Program
    62. {
    63. public static void Main(string[] args)
    64. {
    65. var words = Console.ReadLine().Split(' ');
    66.  
    67. Console.WriteLine($"Distance between words {words[0]} and {words[1]} using brute-force algorithm:");
    68. Console.WriteLine(LevenshteinBruteForce.Calculate(words[0], words[1]));
    69. }
    70. }
    71. }
    72.