-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
91 lines (82 loc) · 1.77 KB
/
Copy pathTrie.cpp
File metadata and controls
91 lines (82 loc) · 1.77 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
#include"import.h"
using namespace std;
class TrieNode {
public:
char val;
bool isLeaf; // if it is end value of the prefix
int numShared;
vector<TrieNode*> children;
TrieNode() :val(' '), isLeaf(false), numShared(0) {}
TrieNode(char ch) : val(ch), isLeaf(false), numShared(0) {}
TrieNode* subNode(char ch) {
if (!children.empty()) {
for (auto child : children) {
if (child->val == ch)
return child;
}
}
return nullptr;
}
~TrieNode() {
for (auto child : children)
delete child;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
if (search(word)) return;
TrieNode* curr = root;
for (auto ch : word) {
TrieNode* child = curr->subNode(ch);
if (child != nullptr) {
curr = child;
}
else {
TrieNode *newNode = new TrieNode(ch);
curr->children.push_back(newNode);
curr = newNode;
}
++curr->numShared;
}
curr->isLeaf = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* curr = root;
for (auto ch : word) {
curr = curr->subNode(ch);
if (curr == nullptr)
return false;
}
return curr->isLeaf == true;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* curr = root;
for (auto ch : prefix) {
curr = curr->subNode(ch);
if (curr == nullptr)
return false;
}
return true;
}
~Trie() {
delete root;
}
private:
TrieNode* root;
};
int main() {
Trie trie;
trie.insert("somestring");
trie.insert("some");
cout << trie.startsWith("so");
return 0;
}
// Your Trie object will be instantiated and called as such: