-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathautoComplete.cpp
119 lines (87 loc) · 2.39 KB
/
autoComplete.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
110
111
112
113
114
115
116
117
118
119
#include <bits/stdc++.h>
using namespace std;
class node{
public:
unordered_map<char,node*> children;
int count;
char data;
bool terminal;
node(char d){
data = d;
terminal = false;
count = 0;
}
};
class Trie{
public:
node * root;
Trie(){
root = new node('\0');
}
void insert(char * word) {
node *temp = root;
for(int i = 0; word[i]!= '\0';i++){
char ch = word[i];
if(temp->children.count(ch)){
temp = temp->children[ch];
}else {
node *n = new node(ch);
temp->children[ch] = n;
temp = n;
}
temp->count+=1;
}
temp->terminal = true;
}
vector<string> advanceSearch(char *prefix){
vector<string> autoCompWords;
node * currentNode = root;
int index = -1;
for(int i = 0; prefix[i] != '\0';i++){
index+=1;
if(currentNode->children.count(prefix[i])){
currentNode = currentNode->children[prefix[i]];
} else{
return autoCompWords;
}
}
searchWords(currentNode,autoCompWords,prefix,index+1);
return autoCompWords;
}
void searchWords(node * currentNode, vector<string> & autoCompWords,
char*prefix,int i){
if (currentNode == NULL) return;
if(currentNode->terminal== true){
prefix[i] = '\0';
cout<<prefix<<endl;
autoCompWords.push_back(prefix);
return;
}
for(auto k = currentNode->children.begin();
k!=currentNode->children.end();k++){
// cout<<k->first;
prefix[i] = k->first;
// cout<<prefix<<endl;
searchWords(k->second,autoCompWords,prefix,i+1);
}
}
};
int main(){
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
freopen("output.txt", "w", stdout);
#endif
Trie t;
char words[][10] = {"cobra","dog","dove","duck"};
for(int i =0;i<4;i++){
t.insert(words[i]);
}
char prefix[100];
prefix[0] = 'd';
prefix[1] = 'o';
vector<string> ans;
ans = t.advanceSearch(prefix);
return 0;
}