File tree 1 file changed +61
-0
lines changed
0208-implement-trie-prefix-tree
1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ class trieNode {
2
+ public:
3
+ bool isEnd;
4
+ trieNode* child[26 ];
5
+ trieNode () {
6
+ isEnd = false ;
7
+ fill (begin (child), end (child), nullptr );
8
+ }
9
+ };
10
+
11
+ class Trie {
12
+ public:
13
+ trieNode* root;
14
+ Trie () {
15
+ root = new trieNode ();
16
+ }
17
+
18
+ int getIdx (char c) {
19
+ return c - ' a' ;
20
+ }
21
+
22
+ void insert (string word) {
23
+ trieNode* node = root;
24
+ for (auto & c: word) {
25
+ int idx = getIdx (c);
26
+ if (!node->child [idx]) {
27
+ node->child [idx] = new trieNode ();
28
+ }
29
+ node = node->child [idx];
30
+ }
31
+ node->isEnd = true ;
32
+ }
33
+
34
+ bool search (string word) {
35
+ trieNode* node = root;
36
+ for (auto & c : word) {
37
+ int idx = getIdx (c);
38
+ if (!node->child [idx]) return false ;
39
+ node = node->child [idx];
40
+ }
41
+ return node->isEnd ;
42
+ }
43
+
44
+ bool startsWith (string prefix) {
45
+ trieNode* node = root;
46
+ for (auto & c: prefix) {
47
+ int idx = getIdx (c);
48
+ if (!node->child [idx]) return false ;
49
+ node = node->child [idx];
50
+ }
51
+ return true ;
52
+ }
53
+ };
54
+
55
+ /* *
56
+ * Your Trie object will be instantiated and called as such:
57
+ * Trie* obj = new Trie();
58
+ * obj->insert(word);
59
+ * bool param_2 = obj->search(word);
60
+ * bool param_3 = obj->startsWith(prefix);
61
+ */
You can’t perform that action at this time.
0 commit comments