File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+
3
+ using namespace std ;
4
+
5
+ class TrieNode {
6
+ public:
7
+ int nextNode[26 ];
8
+ bool isEnd;
9
+ TrieNode () : isEnd(false ) { memset (nextNode, -1 , sizeof (nextNode)); }
10
+ };
11
+
12
+ class Trie {
13
+ public:
14
+ vector<TrieNode> trie;
15
+
16
+ Trie () { trie.push_back (TrieNode ()); }
17
+
18
+ void insert (string word) {
19
+ int node = 0 ;
20
+ for (const char &c : word) {
21
+ if (trie[node].nextNode [c - ' a' ] == -1 ) {
22
+ trie[node].nextNode [c - ' a' ] = trie.size ();
23
+ trie.push_back (TrieNode ());
24
+ }
25
+ node = trie[node].nextNode [c - ' a' ];
26
+ }
27
+ trie[node].isEnd = true ;
28
+ }
29
+
30
+ bool search (string word) {
31
+ int node = 0 ;
32
+ for (const char &c : word) {
33
+ if (trie[node].nextNode [c - ' a' ] == -1 ) {
34
+ return false ;
35
+ }
36
+ node = trie[node].nextNode [c - ' a' ];
37
+ }
38
+ return trie[node].isEnd ;
39
+ }
40
+
41
+ bool startsWith (string prefix) {
42
+ int node = 0 ;
43
+ for (const char &c : prefix) {
44
+ if (trie[node].nextNode [c - ' a' ] == -1 ) {
45
+ return false ;
46
+ }
47
+ node = trie[node].nextNode [c - ' a' ];
48
+ }
49
+ return true ;
50
+ }
51
+ };
You can’t perform that action at this time.
0 commit comments