Skip to content

Commit 09bdc03

Browse files
committed
Time: 52 ms (93.35%), Space: 45 MB (58.33%) - LeetHub
1 parent a175a70 commit 09bdc03

File tree

1 file changed

+46
-20
lines changed

1 file changed

+46
-20
lines changed

0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.cpp

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,72 @@
1-
class Trie {
2-
public:
1+
class Node{
32

4-
struct Node{
5-
Node *Child[26] = {nullptr};
6-
bool isWord = false;
7-
};
3+
public:
84

9-
Node* root = new Node();
5+
Node* child[26] = {nullptr};
6+
bool isWord = false;
107

11-
Trie() {
8+
bool containsKey(char ch)
9+
{
10+
return (child[ch-'a'] != nullptr);
11+
}
1212

13+
void put(char ch, Node* node)
14+
{
15+
child[ch-'a'] = node;
16+
}
17+
18+
Node* get(char ch)
19+
{
20+
return child[ch - 'a'];
21+
}
22+
23+
void setEnd(){
24+
isWord = true;
25+
}
26+
27+
bool isEnd(){
28+
return isWord;
29+
}
30+
};
31+
32+
class Trie {
33+
public:
34+
private:
35+
Node* root;
36+
public:
37+
Trie() {
38+
root = new Node();
1339
}
1440

1541
void insert(string word) {
16-
Node * temp = root;
17-
for(int i= 0; i<word.size();++i)
42+
Node *temp = root;
43+
for(int i = 0; i < word.size(); ++i)
1844
{
19-
if(!temp->Child[word[i]-'a'])
20-
temp->Child[word[i]-'a'] = new Node();
21-
temp = temp->Child[word[i]-'a'];
45+
if(!temp->containsKey(word[i]))
46+
temp->put(word[i],new Node());
47+
temp = temp->get(word[i]);
2248
}
23-
temp->isWord = true;
49+
temp->setEnd();
2450
}
2551

2652
bool search(string word) {
2753
Node *temp = root;
28-
for(int i = 0; i < word.size(); ++i)
54+
for(int i = 0; i<word.size(); ++i)
2955
{
30-
if(!temp->Child[word[i]-'a'])
56+
if(!temp->containsKey(word[i]))
3157
return false;
32-
temp = temp->Child[word[i]-'a'];
58+
temp = temp->get(word[i]);
3359
}
34-
return temp->isWord;
60+
return temp->isEnd();
3561
}
3662

3763
bool startsWith(string prefix) {
3864
Node *temp = root;
3965
for(int i = 0; i<prefix.size(); ++i)
4066
{
41-
if(!temp->Child[prefix[i] - 'a'])
67+
if(!temp->containsKey(prefix[i]))
4268
return false;
43-
temp = temp->Child[prefix[i] - 'a'];
69+
temp = temp->get(prefix[i]);
4470
}
4571
return true;
4672
}

0 commit comments

Comments
 (0)