-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathSuffixTree.cs
96 lines (76 loc) · 2.44 KB
/
SuffixTree.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections;
using System.Collections.Generic;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A suffix tree implementation using a trie.
/// </summary>
public class SuffixTree<T> : IEnumerable<T[]>
{
private readonly HashSet<T[]> items = new(new ArrayComparer<T>());
private readonly Trie<T> trie;
public SuffixTree()
{
trie = new Trie<T>();
Count = 0;
}
public int Count { private set; get; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T[]> GetEnumerator()
{
return items.GetEnumerator();
}
/// <summary>
/// Insert a new entry to this suffix tree.
/// Time complexity: O(m^2) where m is the length of entry array.
/// </summary>
public void Insert(T[] entry)
{
if (entry == null) throw new ArgumentException();
if (items.Contains(entry)) throw new Exception("Item exists.");
for (var i = 0; i < entry.Length; i++)
{
var suffix = new T[entry.Length - i];
Array.Copy(entry, i, suffix, 0, entry.Length - i);
trie.Insert(suffix);
}
items.Add(entry);
Count++;
}
/// <summary>
/// Deletes an existing entry from this suffix tree.
/// Time complexity: O(m^2) where m is the length of entry array.
/// </summary>
public void Delete(T[] entry)
{
if (entry == null) throw new ArgumentException();
if (!items.Contains(entry)) throw new Exception("Item does'nt exist.");
for (var i = 0; i < entry.Length; i++)
{
var suffix = new T[entry.Length - i];
Array.Copy(entry, i, suffix, 0, entry.Length - i);
trie.Delete(suffix);
}
items.Remove(entry);
Count--;
}
/// <summary>
/// Returns true if the given entry pattern is in this suffix tree.
/// Time complexity: O(e) where e is the length of the given entry.
/// </summary>
public bool Contains(T[] pattern)
{
return trie.ContainsPrefix(pattern);
}
/// <summary>
/// Returns all sub-entries that starts with this search pattern.
/// Time complexity: O(rm) where r is the number of results and m is the average length of each entry.
/// </summary>
public List<T[]> StartsWith(T[] pattern)
{
return trie.StartsWith(pattern);
}
}