Skip to content

Commit fc606b8

Browse files
committed
🌲(LEETCODE) Trie (Prefix Tree)
1 parent ce92baf commit fc606b8

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Trie
2+
{
3+
4+
Trie *children[26];
5+
bool isEndOfWord;
6+
7+
public:
8+
/** Initialize your data structure here. */
9+
Trie()
10+
{
11+
12+
isEndOfWord = false;
13+
for (int i = 0; i < 26; i++)
14+
children[i] = NULL;
15+
}
16+
17+
/** Inserts a word into the trie. */
18+
void insert(string word)
19+
{
20+
Trie *curr = this;
21+
for (char c : word)
22+
{
23+
if (!(curr->children[c - 'a']))
24+
{
25+
curr->children[c - 'a'] = new Trie;
26+
}
27+
curr = curr->children[c - 'a'];
28+
}
29+
curr->isEndOfWord = true;
30+
}
31+
32+
/** Returns if the word is in the trie. */
33+
bool search(string word)
34+
{
35+
Trie *curr = this;
36+
for (char c : word)
37+
{
38+
curr = curr->children[c - 'a'];
39+
if (!curr)
40+
return false;
41+
}
42+
return curr->isEndOfWord;
43+
}
44+
45+
/** Returns if there is any word in the trie that starts with the given prefix. */
46+
bool startsWith(string prefix)
47+
{
48+
Trie *curr = this;
49+
for (char c : prefix)
50+
{
51+
curr = curr->children[c - 'a'];
52+
if (!curr)
53+
return false;
54+
}
55+
return true;
56+
}
57+
};
58+
59+
/**
60+
* Your Trie object will be instantiated and called as such:
61+
* Trie* obj = new Trie();
62+
* obj->insert(word);
63+
* bool param_2 = obj->search(word);
64+
* bool param_3 = obj->startsWith(prefix);
65+
*/

0 commit comments

Comments
 (0)