forked from vedant781999/Array_operation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigital_Dictionary_Trie.cpp
More file actions
105 lines (98 loc) · 1.8 KB
/
Digital_Dictionary_Trie.cpp
File metadata and controls
105 lines (98 loc) · 1.8 KB
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
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
node *next[26];
bool end;
node()
{
for (int i = 0; i < 26; i++)
{
next[i] = NULL;
}
end = false;
}
};
class Trie
{
private:
node *root;
public:
Trie()
{
root = new node();
}
void insert(string &s)
{
node *it = root;
for (auto c : s)
{
if (!it->next[c - 'a'])
{
it->next[c - 'a'] = new node();
}
it = it->next[c - 'a'];
}
it->end = true;
}
void find(string &s)
{
node *it = root;
for (auto c : s)
{
if (!it->next[c - 'a'])
{
cout << "No Suggestion\n";
insert(s);
return;
}
it = it->next[c - 'a'];
}
vector<string> res;
printall(it, s, res, "");
for (auto c : res)
{
cout << s << c << "\n";
}
}
void printall(node *it, string &s, vector<string> &res, string curr)
{
if (it == NULL)
{
return;
}
if (it->end)
{
res.push_back(curr);
}
for (int i = 0; i < 26; i++)
{
if (it->next[i])
{
printall(it->next[i], s, res, curr + char('a' + i));
}
}
}
};
int main()
{
Trie t;
int n;
cin >> n;
vector<string> a(n);
for (auto &i : a)
{
cin >> i;
t.insert(i);
}
int q;
cin >> q;
while (q--)
{
string s;
cin >> s;
t.find(s);
}
return 0;
}