Trie
Loading...
Searching...
No Matches
Trie.hpp
Go to the documentation of this file.
1/*
2 MIT License
3
4 Copyright(c) 2023 George Fotopoulos
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files(the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions :
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23*/
24
25#include <memory>
26#include <string>
27#include <unordered_map>
28
29template<typename T>
30class trie_t {
31public:
32 trie_t() = default;
33
34 void insert(const std::basic_string<T> &word) {
35 trie_t *current = this;
36 for (T character: word) {
37 if (current->m_children.find(character) == current->m_children.end()) {
38 current->m_children[character] = std::make_shared<trie_t>();
39 }
40 current = current->m_children[character].get();
41 }
42 current->m_is_end_of_word = true;
43 }
44
45 bool search(const std::basic_string<T> &word) {
46 trie_t *current = this;
47 for (T character: word) {
48 if (current->m_children.find(character) == current->m_children.end()) {
49 return false;
50 }
51 current = current->m_children[character].get();
52 }
53 return current->m_is_end_of_word;
54 }
55
56 bool starts_with(const std::basic_string<T> &prefix) {
57 trie_t *current = this;
58 for (T character: prefix) {
59 if (current->m_children.find(character) == current->m_children.end()) {
60 return false;
61 }
62 current = current->m_children[character].get();
63 }
64 return true;
65 }
66
67private:
68 std::unordered_map<T, std::shared_ptr<trie_t>> m_children;
69 bool m_is_end_of_word = false;
70};
Definition: Trie.hpp:30
bool search(const std::basic_string< T > &word)
Definition: Trie.hpp:45
bool starts_with(const std::basic_string< T > &prefix)
Definition: Trie.hpp:56
trie_t()=default
void insert(const std::basic_string< T > &word)
Definition: Trie.hpp:34