-
Notifications
You must be signed in to change notification settings - Fork 546
Expand file tree
/
Copy pathTrie.cpp
More file actions
82 lines (69 loc) · 2.12 KB
/
Trie.cpp
File metadata and controls
82 lines (69 loc) · 2.12 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
// Trie Implementation in C++
#include <iostream>
#include <unordered_map>
using namespace std;
// Trie node structure
class TrieNode {
public:
bool isEndOfWord;
unordered_map<char, TrieNode*> children;
TrieNode() {
isEndOfWord = false;
}
};
// Trie class
class Trie {
private:
TrieNode* root;
public:
// Constructor
Trie() {
root = new TrieNode();
}
// Insert a word into the Trie
void insert(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.find(ch) == current->children.end()) {
current->children[ch] = new TrieNode();
}
current = current->children[ch];
}
current->isEndOfWord = true;
}
// Search for a word in the Trie
bool search(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.find(ch) == current->children.end()) {
return false;
}
current = current->children[ch];
}
return current->isEndOfWord;
}
// Check if any word in the Trie starts with the given prefix
bool startsWith(string prefix) {
TrieNode* current = root;
for (char ch : prefix) {
if (current->children.find(ch) == current->children.end()) {
return false;
}
current = current->children[ch];
}
return true;
}
};
// Main function to demonstrate Trie operations
int main() {
Trie trie;
trie.insert("apple");
trie.insert("app");
trie.insert("bat");
trie.insert("batman");
cout << (trie.search("app") ? "Found 'app'" : "'app' not found") << endl; // Output: Found 'app'
cout << (trie.search("batman") ? "Found 'batman'" : "'batman' not found") << endl; // Output: Found 'batman'
cout << (trie.startsWith("bat") ? "Prefix 'bat' exists" : "Prefix 'bat' doesn't exist") << endl; // Output: Prefix 'bat' exists
cout << (trie.search("batwoman") ? "Found 'batwoman'" : "'batwoman' not found") << endl; // Output: 'batwoman' not found
return 0;
}