|
| 1 | +namespace Common.Algorithm.Core.Text.Distance.Calculators; |
| 2 | + |
| 3 | +public class LCS : IDistanceCalculator |
| 4 | +{ |
| 5 | + private int Width { get; set; } |
| 6 | + |
| 7 | + private int Height { get; set; } |
| 8 | + |
| 9 | + public DistanceInfo GetDistanceInfo(List<string> inputs, CalculationOptions? options = null) |
| 10 | + { |
| 11 | + if (inputs.Count != 2) |
| 12 | + throw new ArgumentOutOfRangeException( |
| 13 | + nameof(inputs), |
| 14 | + "There should be only two inputs" |
| 15 | + ); |
| 16 | + |
| 17 | + options ??= new(); |
| 18 | + |
| 19 | + var result = GetLcsInfo(inputs[0], inputs[1]); |
| 20 | + |
| 21 | + return new DistanceInfo() |
| 22 | + { |
| 23 | + OriginalInputs = inputs, |
| 24 | + Distance = result.LcsMatchedSubSequences!.Keys.First(), |
| 25 | + LcsInfo = result, |
| 26 | + }; |
| 27 | + } |
| 28 | + |
| 29 | + private LcsInfo GetLcsInfo(string a, string b) |
| 30 | + { |
| 31 | + Width = Math.Max(a.Length, b.Length); |
| 32 | + Height = Math.Min(a.Length, b.Length); |
| 33 | + |
| 34 | + var sa = a.Length > b.Length ? b : a; |
| 35 | + var sb = a.Length > b.Length ? a : b; |
| 36 | + |
| 37 | + var calMatrix = new int[Height + 1, Width + 1]; |
| 38 | + var dirMatrix = new int[Height + 1, Width + 1]; |
| 39 | + |
| 40 | + var results = new List<string>(); |
| 41 | + |
| 42 | + for (var i = 1; i <= Height; ++i) |
| 43 | + for (var j = 1; j <= Width; ++j) |
| 44 | + { |
| 45 | + var same = sa[i - 1] == sb[j - 1]; |
| 46 | + calMatrix[i, j] = ( |
| 47 | + same |
| 48 | + ? calMatrix[i - 1, j - 1] + 1 |
| 49 | + : Math.Max(calMatrix[i, j - 1], calMatrix[i - 1, j]) |
| 50 | + ); |
| 51 | + dirMatrix[i, j] = same ? 1 : (calMatrix[i - 1, j] >= calMatrix[i, j - 1] ? 2 : 3); |
| 52 | + } |
| 53 | + |
| 54 | + for (var i = 0; i < Width; ++i) |
| 55 | + results.Add(""); |
| 56 | + |
| 57 | + for (int j = Width; j >= 1; --j) |
| 58 | + Trace(Width - j, Height, Width - (Width - j)); |
| 59 | + |
| 60 | + var m = new Dictionary<string, int>(); |
| 61 | + foreach (var result in results) |
| 62 | + if (result.Length == results[0].Length) |
| 63 | + m[result] = 1; |
| 64 | + results.Clear(); |
| 65 | + foreach (var pair in m) |
| 66 | + if (pair.Value == 1) |
| 67 | + results.Add(pair.Key); |
| 68 | + |
| 69 | + return new() |
| 70 | + { |
| 71 | + LcsMatchedSubSequences = new Dictionary<int, List<string>> |
| 72 | + { |
| 73 | + { results[0].Length, results }, |
| 74 | + }, |
| 75 | + }; |
| 76 | + |
| 77 | + void Trace(int i, int m, int n) |
| 78 | + { |
| 79 | + if (m == 0 || n == 0) |
| 80 | + return; |
| 81 | + switch (dirMatrix[m, n]) |
| 82 | + { |
| 83 | + case 1: |
| 84 | + Trace(i, m - 1, n - 1); |
| 85 | + results[i] = string.Concat(results[i].Append(sa[m - 1])); |
| 86 | + break; |
| 87 | + case 2: |
| 88 | + Trace(i, m - 1, n); |
| 89 | + break; |
| 90 | + case 3: |
| 91 | + Trace(i, m, n - 1); |
| 92 | + break; |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | +} |
0 commit comments