| 1 |
#ifndef TRIE_HPP |
| 2 |
#define TRIE_HPP |
| 3 |
|
| 4 |
#include <unordered_map> |
| 5 |
#include <vector> |
| 6 |
#include <wx/string.h> |
| 7 |
|
| 8 |
class TrieTree; |
| 9 |
typedef TrieTree TreeNode; |
| 10 |
class TrieTree |
| 11 |
{ |
| 12 |
unordered_map<wxChar, TrieTree*> m_children; |
| 13 |
bool end_of_sequence = false; |
| 14 |
|
| 15 |
public: |
| 16 |
bool is_exact_match() const { return this->end_of_sequence; } |
| 17 |
|
| 18 |
~TrieTree() |
| 19 |
{ |
| 20 |
for(auto& vt : m_children) { |
| 21 |
delete vt.second; |
| 22 |
} |
| 23 |
m_children.clear(); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* @brief insert a sequence into the tree |
| 28 |
*/ |
| 29 |
void insert(const wxString& sequence) |
| 30 |
{ |
| 31 |
TrieTree* cur = this; |
| 32 |
for(const wxChar& d : sequence) { |
| 33 |
if(cur->m_children.count(d) == 0) { |
| 34 |
cur->m_children.insert({ d, new TrieTree() }); |
| 35 |
} |
| 36 |
cur = cur->m_children[d]; |
| 37 |
} |
| 38 |
|
| 39 |
// mark the last node as a "end of sequence" |
| 40 |
cur->end_of_sequence = true; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* @brief return if the tree contains a given sequence |
| 45 |
*/ |
| 46 |
const TreeNode* contains(const wxString& sequence) const |
| 47 |
{ |
| 48 |
const TrieTree* cur = this; |
| 49 |
for(const auto& d : sequence) { |
| 50 |
if(cur->m_children.count(d) == 0) { |
| 51 |
return nullptr; |
| 52 |
} |
| 53 |
cur = cur->m_children.find(d)->second; |
| 54 |
} |
| 55 |
|
| 56 |
// if we reached here, it means that we were able to match the entire |
| 57 |
// sequence, however, we only return true if this entire sequence was |
| 58 |
// inserted and its not a sub sequence of something else |
| 59 |
return cur; |
| 60 |
} |
| 61 |
}; |
| 62 |
#endif // TRIE_HPP |