forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searching_a_word_in_trie.cpp
109 lines (80 loc) · 1.62 KB
/
searching_a_word_in_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
A trie is a tree and each node in it contains the number of pointers equal to the number of
characters of the alphabet. For example, if we assume that all the strings are formed with English
alphabet characters “a” to “z” then each node of the trie contains 26 pointers.
*/
#include<map>
#include<string>
#include<queue>
#include<list>
using namespace std;
class node{
public:
char data;
map<char,node*> m;
bool is_terminal;
node(char c){
data = c;
is_terminal = false;
}
};
class Trie{
node* root;
public:
Trie(){
root = new node('\0');
}
void Addword(char word[]){
node* temp = root;
for(int i=0;word[i]!='\0';i++){
char ch = word[i];
//if not present
if(temp->m.count(ch)==0){
// create link
node* child = new node(ch);
temp->m[ch] = child;
temp = child;
}
else{
// next address
temp = temp->m[ch];
}
}
// last node
temp->is_terminal = true;
}
bool search(char word[]){
node* temp = root;
for(int i=0;word[i]!='\0';i++){
char ch = word[i];
// if present
if(temp->m.count(ch)==1){
temp = temp->m[ch];
}
else{
// not present
return false;
}
}
// not always at last node
return temp->is_terminal;
}
};
int main()
{
Trie T;
T.Addword("adf");
T.Addword("not");
T.Addword("nott");
char word[1000];
cin >> word;
cout << boolalpha<<T.search(word);
return 0;
}
/*
Test Case :
Input : adf
Output : true
Time Complexity : O(L), where L is the length of the string to be searched.
Time Complexity : O(1)
*/