This repository has been 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
/
Directed_Acyclic_Word_Graph.cpp
69 lines (69 loc) · 1.94 KB
/
Directed_Acyclic_Word_Graph.cpp
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
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <queue>
class DAWG {
private:
struct Node {
std::unordered_map<char, Node*> children;
bool isEndOfWord;
Node() : isEndOfWord(false) {}
};
Node* root;
public:
DAWG() : root(new Node()) {}
~DAWG() {
destroy(root);
}
void insert(const std::string& word) {
insertHelper(root, word, 0);
}
bool search(const std::string& word) const {
return searchHelper(root, word, 0);
}
private:
void insertHelper(Node* current, const std::string& word, size_t index) {
if (index == word.length()) {
current->isEndOfWord = true;
return;
}
char ch = word[index];
if (current->children.find(ch) == current->children.end()) {
current->children[ch] = new Node();
}
insertHelper(current->children[ch], word, index + 1);
}
bool searchHelper(const Node* current, const std::string& word, size_t index) const {
if (index == word.length()) {
return current->isEndOfWord;
}
char ch = word[index];
if (current->children.find(ch) == current->children.end()) {
return false;
}
return searchHelper(current->children.at(ch), word, index + 1);
}
void destroy(Node* current) {
for (auto& pair : current->children) {
destroy(pair.second);
}
delete current;
}
};
int main() {
DAWG dawg;
std::cout << "Enter words to insert:" << std::endl;
std::string word;
while (std::getline(std::cin, word) && !word.empty()) {
dawg.insert(word);
}
std::cout << "Enter a word to search:" << std::endl;
std::cin >> word;
if (dawg.search(word)) {
std::cout << "The word is present!" << std::endl;
} else {
std::cout << "The word is not present!" << std::endl;
}
return 0;
}