File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments