Skip to content

Commit 31f323e

Browse files
authored
Merge pull request neetcode-gh#84 from Pegasus02K/patch-9
Create 208-Implement-Trie.cpp
2 parents d9d562f + 66c0df9 commit 31f323e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

cpp/208-Implement-Trie.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
struct TrieNode {
2+
TrieNode* children[26];
3+
bool isWordEnd;
4+
5+
TrieNode() : isWordEnd(false) {
6+
for (int i = 0; i < 26; ++i)
7+
children[i] = nullptr;
8+
}
9+
};
10+
11+
class Trie {
12+
private:
13+
TrieNode* root;
14+
public:
15+
Trie() {
16+
root = new TrieNode;
17+
}
18+
19+
void insert(string word) {
20+
TrieNode* cur = root;
21+
22+
int idx;
23+
for (int i = 0; i < word.size(); ++i) {
24+
idx = word[i] - 'a';
25+
if (cur->children[idx] == nullptr)
26+
cur->children[idx] = new TrieNode;
27+
cur = cur->children[idx];
28+
}
29+
// mark the last node as end of a word
30+
cur->isWordEnd = true;
31+
}
32+
33+
bool search(string word) {
34+
TrieNode* cur = root;
35+
36+
int idx;
37+
for (int i = 0; i < word.size(); ++i) {
38+
idx = word[i] - 'a';
39+
if (cur->children[idx] == nullptr)
40+
return false;
41+
cur = cur->children[idx];
42+
}
43+
// check if the node is end of any word
44+
return cur->isWordEnd;
45+
}
46+
47+
bool startsWith(string prefix) {
48+
TrieNode* cur = root;
49+
50+
int idx;
51+
for (int i = 0; i < prefix.size(); ++i) {
52+
idx = prefix[i] - 'a';
53+
if (cur->children[idx] == nullptr)
54+
return false;
55+
cur = cur->children[idx];
56+
}
57+
// only need to check if the node exists
58+
return true;
59+
}
60+
};

0 commit comments

Comments
 (0)