-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrieImpl.cpp
86 lines (71 loc) · 1.55 KB
/
trieImpl.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
#include<bits/stdc++.h>
using namespace std;
class TrieNode {
public:
map<char, TrieNode*> mp;
bool endOfWord;
TrieNode() {
this->endOfWord = false;
}
};
vector<string> global;
void construct(TrieNode* root, vector<string>& W) {
for (string word : W) {
TrieNode* temp = root;
for (int i = 0; i < word.length(); i++) {
if (temp->mp.find(word[i]) != temp->mp.end()) {
temp = temp->mp[word[i]];
}
else {
temp->mp[word[i]] = new TrieNode();
temp = temp->mp[word[i]];
}
if (i == word.length() - 1) {
temp->endOfWord = true;
}
}
}
}
TrieNode* findFollowUpNode(string &s, TrieNode* root) {
TrieNode* temp = root;
for (int i = 0; i < s.length(); i++) {
if (temp->mp.find(s[i]) != temp->mp.end()) {
temp = temp->mp[s[i]];
}
else return NULL;
}
return temp;
}
void recurPrint(TrieNode* root,string s) {
TrieNode* temp = root;
if(root->endOfWord){
global.push_back(s);
}
for(auto itr=temp->mp.begin();itr!=temp->mp.end();itr++){
s.push_back(itr->first);
recurPrint(itr->second,s);
s.pop_back();
}
}
string startsWith(string s, TrieNode* root) {
TrieNode* temp = findFollowUpNode(s, root);
recurPrint(temp,s);
for(auto w: global){
cout<<w<<"\n";
}
return "===========End of Result=============";
}
signed main() {
int n;
cin >> n;
vector<string> words(n);
for (int i = 0; i < n; i++) {
cin >> words[i];
}
TrieNode* root = new TrieNode();
construct(root, words);
string s = "ca";
cout<<"Search results for "<<s<<'\n';
cout<<"-----------------------------"<<'\n';
cout << startsWith(s, root);
}