-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTrie.cpp
More file actions
89 lines (82 loc) · 1.15 KB
/
Trie.cpp
File metadata and controls
89 lines (82 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
class Node
{
public:
char data;
unordered_map<char,Node*> children;
bool terminal;
Node(char d)
{
data=d;
terminal=false;
}
};
class Trie
{
Node* root;
int cnt;//denotes no of words inserted
public:
Trie()
{
root=new Node('\0');
cnt=0;
}
void insert(string w)
{
Node* temp=root;
for(int i=0;i<w.length();i++)
{
char ch=w[i];
if(temp->children[ch])//checking if that character exists
{
temp=temp->children[ch];
}
else
{
Node* newnode=new Node(ch);
temp->children[ch]=newnode;
temp=newnode;
}
}
temp->terminal=true;//word ends here
}
bool find(string w)
{
Node* temp=root;
for(int i=0;i<w.size();i++)
{
char ch=w[i];
if(temp->children.count(ch)==0)
{
return false;
}
else
{
temp=temp->children[ch];
}
}
return temp->terminal;
}
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output1.txt","w",stdout);
#endif
Trie t;
vector<string> v;
int n;
cin>>n;
while(n--)
{ string s;
cin>>s;
t.insert(s);
}
string ss;
cin>>ss;
cout<<t.find(ss);
return 0;
}