-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
90 lines (73 loc) · 1.79 KB
/
Trie.cpp
File metadata and controls
90 lines (73 loc) · 1.79 KB
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
#include <cctype>
#include "Trie.h"
using namespace std;
void Trie::insert(const string& word, const vector<string>& definitions) {
TrieNode* letter = root;
for (char c : word) {
c = tolower(c);
if (c < 'a' || c > 'z')
continue;
int index = c - 'a';
if (!letter->alphabet[index]) {
letter->alphabet[index] = new TrieNode();
}
letter = letter->alphabet[index];
}
letter->endOfWord = true;
letter->definitions = definitions;
}
vector<string> Trie::search(string& word) {
TrieNode* letter = root;
for (char c : word) {
c = tolower(c);
if (c < 'a' || c > 'z')
continue;
int index = c - 'a';
if (!letter->alphabet[index]) {
cout << "Word not found." << endl;
return {};
}
letter = letter->alphabet[index];
}
if (letter->endOfWord) {
return letter->definitions;
}
cout << "Word not found." << endl;
return {};
}
void Trie::pushWords(TrieNode* node, string word, vector<string>& matches) {
if (node->endOfWord)
matches.push_back(word);
for (int i = 0; i < 26; i++) {
if (node->alphabet[i]) {
char c = i + 'a';
pushWords(node->alphabet[i], word + c, matches);
}
}
}
vector<string> Trie::prefix(string& prefix) {
TrieNode* letter = root;
for (char c : prefix) {
c = tolower(c);
int index = c - 'a';
if (!letter->alphabet[index]) {
cout << "No matches for entered prefix." << endl;
return {};
}
letter = letter->alphabet[index];
}
vector<string> matchingWords;
pushWords(letter, prefix, matchingWords);
return matchingWords;
}
void Trie::destruct(TrieNode* root) {
if (root == nullptr)
return;
for (int i = 0; i < 26; i++)
if (root->alphabet[i])
destruct(root->alphabet[i]);
delete root;
}
Trie::~Trie() {
destruct(root);
}