-
Notifications
You must be signed in to change notification settings - Fork 12
/
Trie Pointer.cpp
72 lines (69 loc) · 1.47 KB
/
Trie Pointer.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
/**
Name : Trie with Dynamic memory
Time complexity : o((number of words)*(maximum lenght))
*/
/// Trie form shafaetsplanet
struct node {
bool endmark;
node* next[26 + 1];
node()
{
endmark = false;
for (int i = 0; i < 26; i++)
next[i] = NULL;
}
} * root;
void insert(char* str, int len)
{
node* curr = root;
for (int i = 0; i < len; i++) {
int id = str[i] - 'a';
if (curr->next[id] == NULL)
curr->next[id] = new node();
curr = curr->next[id];
}
curr->endmark = true;
}
bool search(char* str, int len)
{
node* curr = root;
for (int i = 0; i < len; i++) {
int id = str[i] - 'a';
if (curr->next[id] == NULL)
return false;
curr = curr->next[id];
}
return curr->endmark;
}
void del(node* cur)
{
for (int i = 0; i < 26; i++)
if (cur->next[i])
del(cur->next[i]);
delete (cur);
}
int main()
{
puts("ENTER NUMBER OF WORDS");
root = new node();
int num_word;
cin >> num_word;
for (int i = 1; i <= num_word; i++) {
char str[50];
scanf("%s", str);
insert(str, strlen(str));
}
puts("ENTER NUMBER OF QUERY";);
int query;
cin >> query;
for (int i = 1; i <= query; i++) {
char str[50];
scanf("%s", str);
if (search(str, strlen(str)))
puts("FOUND");
else
puts("NOT FOUND");
}
del(root);
return 0;
}