-
Notifications
You must be signed in to change notification settings - Fork 0
/
acg_trie_36.1.cpp
76 lines (66 loc) · 1.6 KB
/
acg_trie_36.1.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
// #include <iostream>
// #include <vector>
#include<bits/stdc++.h>
using namespace std;
class Trie{
public:
class node{
public:
bool end;
node*next[26];
node(){
end = false;
for(int i=0;i<26;i++){
next[i] = NULL;
}
}
};
node * trie;
Trie(){
trie = new node();
}
void insert(string word){
int i=0;
node * it = trie;
while(i<word.size()){
if(it->next[word[i]-'a'] == NULL){ // if node doesnt exist
it->next[word[i]-'a'] = new node();
}
it = it->next[word[i]-'a'];
i++;
}
it->end =true;
}
bool search(string word){
int i=0;
node* it = trie;
while(i<word.size()){
if(it->next[word[i]-'a'] == NULL)
return false;
it = it->next[word[i]-'a'];
i++;
}
return it->end;
}
} ;
int main()
{ Trie *mytrie = new Trie();
vector<string> words= { "ayush","daasi"};
for(auto w:words){
mytrie->insert(w);
}
if(mytrie->search("madhav")){
cout<<"madhav found\n";
}
else{
cout<<"madhav not found \n";
}
if(mytrie->search("ayush")){
cout<<"ayush found\n";
}
else{
cout<<"ayush not found \n";
}
cout<<endl;
return 0;
}