Skip to content

Commit 75e829d

Browse files
committed
Time: 80 ms (83.62%), Space: 45 MB (70.46%) - LeetHub
1 parent c9f1e50 commit 75e829d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Trie {
2+
public:
3+
4+
struct Node{
5+
Node *Child[26] = {nullptr};
6+
bool isWord = false;
7+
};
8+
9+
Node* root = new Node();
10+
11+
Trie() {
12+
13+
}
14+
15+
void insert(string word) {
16+
Node * temp = root;
17+
for(int i= 0; i<word.size();++i)
18+
{
19+
if(!temp->Child[word[i]-'a'])
20+
temp->Child[word[i]-'a'] = new Node();
21+
temp = temp->Child[word[i]-'a'];
22+
}
23+
temp->isWord = true;
24+
}
25+
26+
bool search(string word) {
27+
Node *temp = root;
28+
for(int i = 0; i < word.size(); ++i)
29+
{
30+
if(!temp->Child[word[i]-'a'])
31+
return false;
32+
temp = temp->Child[word[i]-'a'];
33+
}
34+
return temp->isWord;
35+
}
36+
37+
bool startsWith(string prefix) {
38+
Node *temp = root;
39+
for(int i = 0; i<prefix.size(); ++i)
40+
{
41+
if(!temp->Child[prefix[i] - 'a'])
42+
return false;
43+
temp = temp->Child[prefix[i] - 'a'];
44+
}
45+
return true;
46+
}
47+
};
48+
49+
/**
50+
* Your Trie object will be instantiated and called as such:
51+
* Trie* obj = new Trie();
52+
* obj->insert(word);
53+
* bool param_2 = obj->search(word);
54+
* bool param_3 = obj->startsWith(prefix);
55+
*/

0 commit comments

Comments
 (0)