This repository was archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHash_Array_Mapped_Trie.cpp
More file actions
95 lines (95 loc) · 2.58 KB
/
Hash_Array_Mapped_Trie.cpp
File metadata and controls
95 lines (95 loc) · 2.58 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
91
92
93
94
95
#include <iostream>
#include <unordered_map>
#include <bitset>
#include <vector>
const int MAX_BRANCHING_FACTOR = 32;
class HAMTNode {
private:
std::unordered_map<char, HAMTNode*> children;
bool isEndOfWord;
public:
HAMTNode() : isEndOfWord(false) {}
void insert(const std::string& key) {
if (key.empty()) {
isEndOfWord = true;
return;
}
char firstChar = key[0];
std::string rest = key.substr(1);
if (children.find(firstChar) == children.end()) {
children[firstChar] = new HAMTNode();
}
children[firstChar]->insert(rest);
}
bool search(const std::string& key) const {
if (key.empty()) {
return isEndOfWord;
}
char firstChar = key[0];
std::string rest = key.substr(1);
if (children.find(firstChar) != children.end()) {
return children.at(firstChar)->search(rest);
}
return false;
}
void remove(const std::string& key) {
if (key.empty()) {
isEndOfWord = false;
return;
}
char firstChar = key[0];
std::string rest = key.substr(1);
if (children.find(firstChar) != children.end()) {
children[firstChar]->remove(rest);
if (children[firstChar]->isEmpty()) {
delete children[firstChar];
children.erase(firstChar);
}
}
}
bool isEmpty() const {
return children.empty() && !isEndOfWord;
}
~HAMTNode() {
for (auto& pair : children) {
delete pair.second;
}
}
};
class HashArrayMappedTrie {
private:
HAMTNode* root;
public:
HashArrayMappedTrie() : root(new HAMTNode()) {}
void insert(const std::string& key) {
root->insert(key);
}
bool search(const std::string& key) const {
return root->search(key);
}
void remove(const std::string& key) {
root->remove(key);
}
~HashArrayMappedTrie() {
delete root;
}
};
int main() {
HashArrayMappedTrie hamt;
std::cout << "Enter words to insert:" << std::endl;
std::string word;
while (std::getline(std::cin, word) && !word.empty()) {
hamt.insert(word);
}
std::cout << "Enter a word to search:" << std::endl;
std::cin >> word;
if (hamt.search(word)) {
std::cout << "The word is present!" << std::endl;
} else {
std::cout << "The word is not present!" << std::endl;
}
std::cout << "Enter a word to remove:" << std::endl;
std::cin >> word;
hamt.remove(word);
return 0;
}