|
1 | | -class Trie { |
2 | | -public: |
| 1 | +class Node{ |
3 | 2 |
|
4 | | - struct Node{ |
5 | | - Node *Child[26] = {nullptr}; |
6 | | - bool isWord = false; |
7 | | - }; |
| 3 | + public: |
8 | 4 |
|
9 | | - Node* root = new Node(); |
| 5 | + Node* child[26] = {nullptr}; |
| 6 | + bool isWord = false; |
10 | 7 |
|
11 | | - Trie() { |
| 8 | + bool containsKey(char ch) |
| 9 | + { |
| 10 | + return (child[ch-'a'] != nullptr); |
| 11 | + } |
12 | 12 |
|
| 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(); |
13 | 39 | } |
14 | 40 |
|
15 | 41 | 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) |
18 | 44 | { |
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]); |
22 | 48 | } |
23 | | - temp->isWord = true; |
| 49 | + temp->setEnd(); |
24 | 50 | } |
25 | 51 |
|
26 | 52 | bool search(string word) { |
27 | 53 | Node *temp = root; |
28 | | - for(int i = 0; i < word.size(); ++i) |
| 54 | + for(int i = 0; i<word.size(); ++i) |
29 | 55 | { |
30 | | - if(!temp->Child[word[i]-'a']) |
| 56 | + if(!temp->containsKey(word[i])) |
31 | 57 | return false; |
32 | | - temp = temp->Child[word[i]-'a']; |
| 58 | + temp = temp->get(word[i]); |
33 | 59 | } |
34 | | - return temp->isWord; |
| 60 | + return temp->isEnd(); |
35 | 61 | } |
36 | 62 |
|
37 | 63 | bool startsWith(string prefix) { |
38 | 64 | Node *temp = root; |
39 | 65 | for(int i = 0; i<prefix.size(); ++i) |
40 | 66 | { |
41 | | - if(!temp->Child[prefix[i] - 'a']) |
| 67 | + if(!temp->containsKey(prefix[i])) |
42 | 68 | return false; |
43 | | - temp = temp->Child[prefix[i] - 'a']; |
| 69 | + temp = temp->get(prefix[i]); |
44 | 70 | } |
45 | 71 | return true; |
46 | 72 | } |
|
0 commit comments