forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.cpp
77 lines (62 loc) · 1.72 KB
/
Trie.cpp
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
#include<iostream>
#include <unordered_map>
#define hashmap unordered_map<char,node*>
using namespace std;
class node{
public:
char ch;
bool isTerminal;
hashmap mp;
node(char c){
ch=c;
isTerminal = false;
}
};
class Trie{
node* root;
public :
Trie(){
root= new node('\0');
}
void insertString(string str){
node* temp = root;
int leng = str.length();
for(int i=0;i<leng;i++)
{ if(temp->mp.count(str[i])==0)
{
node* child = new node(str[i]);
temp->mp[str[i]]= child;
temp=child;
}
else{
temp=temp->mp[str[i]];
}
}
temp->isTerminal=true;
}
bool isPresent(string s){
node* temp= root;
int len=s.length();
for(int i=0;i<len;i++){
if(temp->mp.count(s[i])==0)
{
return false;
}
else
{
temp=temp->mp[s[i]];
}
}
return temp->isTerminal;
}
};
int main(){
string sts[]={"apple","ap","app","apps"};
Trie t;
t.insertString(sts[0]);
t.insertString(sts[1]);
t.insertString(sts[2]);
t.insertString(sts[3]);
cout<<"If present "<<t.isPresent("apping")<<endl;
return 0;
}