Skip to content

Commit 77648ea

Browse files
committed
add leetcode implement trie solution
1 parent 0792232 commit 77648ea

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings.
3+
* There are various applications of this data structure, such as autocomplete and spellchecker
4+
*
5+
* Your Trie object will be instantiated and called as such:
6+
* Trie* obj = new Trie();
7+
* obj->insert(word);
8+
* bool param_2 = obj->search(word);
9+
* bool param_3 = obj->startsWith(prefix);
10+
*/
11+
12+
class Trie {
13+
public:
14+
struct TrieNode
15+
{
16+
TrieNode* child[26];
17+
bool isEnd;
18+
TrieNode()
19+
{
20+
isEnd = false;
21+
for(int i = 0; i < 26; i++)
22+
child[i] = NULL;
23+
}
24+
};
25+
26+
TrieNode* root;
27+
28+
Trie() {
29+
root = new TrieNode();
30+
}
31+
32+
void insert(string word) {
33+
TrieNode* curr = root;
34+
for(int i = 0; i < word.length(); i++)
35+
{
36+
int index = word[i] - 'a';
37+
if(curr->child[index] == NULL)
38+
curr->child[index] = new TrieNode();
39+
curr = curr->child[index];
40+
}
41+
curr->isEnd = true;
42+
}
43+
44+
bool search(string word) {
45+
TrieNode* curr = root;
46+
for(int i = 0; i < word.length(); i++)
47+
{
48+
int index = word[i] - 'a';
49+
if(curr->child[index] == NULL)
50+
return false;
51+
curr = curr->child[index];
52+
}
53+
return curr->isEnd;
54+
}
55+
56+
bool startsWith(string prefix) {
57+
TrieNode* curr = root;
58+
for(int i = 0; i < prefix.length(); i++)
59+
{
60+
int index = prefix[i] - 'a';
61+
if(curr->child[index] == NULL)
62+
return false;
63+
curr = curr->child[index];
64+
}
65+
return true;
66+
}
67+
};

0 commit comments

Comments
 (0)