-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLevenshtein.cs
44 lines (42 loc) · 1.21 KB
/
Levenshtein.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
namespace LocalLibrary
{
public class Levenshtein
{
public string Name;
public int Value;
public int Distance(string a, string b)
{
if (string.IsNullOrEmpty(a))
{
return string.IsNullOrEmpty(b) ? 0 : b.Length;
}
if (string.IsNullOrEmpty(b))
{
return a.Length;
}
int lengthA = a.Length;
int lengthB = b.Length;
int[,] matrix = new int[lengthA + 1, lengthB + 1];
for (int i = 0; i <= lengthA; i++)
{
matrix[i, 0] = i;
}
for (int i = 0; i <= lengthB; i++)
{
matrix[0, i] = i;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int cost = (b[j - 1] == a[i - 1]) ? 0 : 1;
matrix[i, j] = Math.Min(
Math.Min(matrix[i - 1, j] + 1, matrix[i, j - 1] + 1),
matrix[i - 1, j - 1] + cost);
}
}
return matrix[lengthA, lengthB];
}
}
}