Skip to content

Commit 5cbdbbb

Browse files
committed
Time: 46 ms (66.47%), Space: 48.6 MB (37.23%) - LeetHub
1 parent bd191aa commit 5cbdbbb

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class trieNode{
2+
public:
3+
bool isEnd;
4+
trieNode* child[26];
5+
trieNode() {
6+
isEnd = false;
7+
fill(begin(child), end(child), nullptr);
8+
}
9+
};
10+
11+
class Trie {
12+
public:
13+
trieNode* root;
14+
Trie() {
15+
root = new trieNode();
16+
}
17+
18+
int getIdx(char c) {
19+
return c - 'a';
20+
}
21+
22+
void insert(string word) {
23+
trieNode* node = root;
24+
for (auto& c: word) {
25+
int idx = getIdx(c);
26+
if (!node->child[idx]) {
27+
node->child[idx] = new trieNode();
28+
}
29+
node = node->child[idx];
30+
}
31+
node->isEnd = true;
32+
}
33+
34+
bool search(string word) {
35+
trieNode* node = root;
36+
for (auto& c : word) {
37+
int idx = getIdx(c);
38+
if (!node->child[idx]) return false;
39+
node = node->child[idx];
40+
}
41+
return node->isEnd;
42+
}
43+
44+
bool startsWith(string prefix) {
45+
trieNode* node = root;
46+
for (auto& c: prefix) {
47+
int idx = getIdx(c);
48+
if (!node->child[idx]) return false;
49+
node = node->child[idx];
50+
}
51+
return true;
52+
}
53+
};
54+
55+
/**
56+
* Your Trie object will be instantiated and called as such:
57+
* Trie* obj = new Trie();
58+
* obj->insert(word);
59+
* bool param_2 = obj->search(word);
60+
* bool param_3 = obj->startsWith(prefix);
61+
*/

0 commit comments

Comments
 (0)