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