File tree Expand file tree Collapse file tree 1 file changed +91
-0
lines changed Expand file tree Collapse file tree 1 file changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ #define pb push_back
3
+ #define eb emplace_back
4
+ #define mp make_pair
5
+ #define mt make_tuple
6
+ #define all (v ) v.begin(),v.end()
7
+ #define PI 3.14159265358979323
8
+ #define endl ' \n '
9
+ #define hashmap unordered_map<char ,node*>
10
+
11
+ using namespace std ;
12
+
13
+ class node {
14
+ public:
15
+ char data;
16
+ hashmap h;
17
+ bool isTerminal;
18
+
19
+ node (char d)
20
+ {
21
+ data=d;
22
+ isTerminal=false ;
23
+ }
24
+
25
+ };
26
+
27
+
28
+
29
+ class Trie {
30
+
31
+ node *root;
32
+
33
+ public:
34
+ Trie (){
35
+ root=new node (' \0 ' );
36
+ }
37
+
38
+ void addWord (char * word)
39
+ {
40
+ node * temp=root;
41
+
42
+ for (int i=0 ;word[i]!=' \0 ' ;i++)
43
+ {
44
+ char ch=word[i];
45
+ if (temp->h .count (ch)==0 )
46
+ {
47
+ node * child=new node (ch);
48
+ temp->h [ch]=child;
49
+ temp=child;
50
+ }else
51
+ temp=temp->h [ch];
52
+ }
53
+ temp->isTerminal =true ;
54
+ }
55
+
56
+ bool search (char * word)
57
+ {
58
+ node * temp=root;
59
+
60
+ for (int i=0 ;word[i]!=' \0 ' ;i++)
61
+ {
62
+ char ch=word[i];
63
+ if (temp->h .count (ch))
64
+ {
65
+ temp=temp->h [ch];
66
+ }
67
+ else
68
+ return false ;
69
+ }
70
+
71
+ if (temp->isTerminal )
72
+ return true ;
73
+ else
74
+ return false ;
75
+ }
76
+
77
+ };
78
+
79
+ int main (){
80
+ // char word[10][100]={"apple","code","vinegar"};
81
+ Trie t;
82
+ t.addWord (" vinegar" );
83
+ t.addWord (" vine" );
84
+ t.addWord (" cinnamon" );
85
+
86
+ cout<<t.search (" vine" )<<endl;
87
+ cout<<t.search (" ape" )<<endl;
88
+
89
+ }
90
+
91
+
You can’t perform that action at this time.
0 commit comments