forked from aryan-02/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.cpp
84 lines (84 loc) · 2 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
78
79
80
81
82
83
84
#include <iostream>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <fstream>
#include <vector>
#include <set>
#include <queue>
#define int long long
#define MOD 100000
#define random (rand()%MOD)
using namespace std;
struct node{
int endofword;
node* next[26];
};
node* newnode(){
node* temp = new node;
temp->endofword = 0;
for(int i = 0;i<26;i++) temp->next[i] = NULL;
return temp;
}
void insert(node* currentnode, string s){
for(int i = 0;i<s.length();i++){
if(currentnode->next[s[i]-'a']!=NULL){
currentnode = currentnode->next[s[i]-'a'];
}
else{
currentnode = currentnode->next[s[i]-'a'] = newnode();
}
}
currentnode->endofword++;
}
bool prefixExists(node* currentnode, string s){
for(int i = 0;i<s.length();i++){
if(currentnode->next[s[i]-'a']!=NULL){
currentnode = currentnode->next[s[i]-'a'];
}
else{
return false;
}
}
return true;
}
bool wordSearch(node* currentnode, string s){
for(int i = 0;i<s.length();i++){
if(currentnode->next[s[i]-'a']!=NULL){
currentnode = currentnode->next[s[i]-'a'];
}
else{
return false;
}
}
return currentnode->endofword>=1?true:false;
}
int32_t main(){
node* root = newnode();
int q;
cin>>q;
while(q--){
int type;
cin>>type;
if(type==1){
string toinsert;
cin>>toinsert;
insert(root, toinsert);
}
else{
string prefixsearch;
cin>>prefixsearch;
bool prexist = prefixExists(root, prefixsearch);
bool wordexist = wordSearch(root, prefixsearch);
if(prexist){
cout<<"Prefix exists"<<endl;
if(wordexist){
cout<<"Word exists"<<endl;
}
}
else{
cout<<"Does not exist"<<endl;
}
}
}
}