-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathautocompleteFeatureUsingTrie.cpp
132 lines (97 loc) · 2.61 KB
/
autocompleteFeatureUsingTrie.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
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
using namespace std;
#define charToIndex(c) ((int)c - (int)'a')
struct TrieNode{
struct TrieNode *children[26];
bool isWordEnd;
};
struct TrieNode *getNode(){
struct TrieNode *newNode = new TrieNode;
newNode -> isWordEnd = false;
for(int i = 0; i < 26; i++){
newNode -> children[i] = nullptr;
}
return newNode;
}
void insert(struct TrieNode *root, string key){
struct TrieNode *ptr = root;
for(int i = 0; i < key.length(); i++){
int index = charToIndex(key[i]);
if(!ptr -> children[index]){
ptr -> children[index] = getNode();
}
ptr = ptr -> children[index];
}
ptr -> isWordEnd = true;
}
bool search(struct TrieNode *root, string key){
struct TrieNode *ptr = root;
for(int i = 0; i < key.length(); i++){
int index = charToIndex(key[i]);
if(!ptr -> children[index])
return false;
ptr = ptr -> children[index];
}
return (ptr and ptr -> isWordEnd);
}
bool isLastNode(struct TrieNode *root){
for(int i = 0; i < 26; i++){
if(root -> children[i])
return false;
}
return true;
}
void suggestionsRec(struct TrieNode *root, string prefix){
if(root -> isWordEnd){
cout << prefix << endl;
}
if(isLastNode(root)){
return;
}
for(int i = 0; i < 26; i++){
if(root -> children[i]){
prefix.push_back(char(97 + i));
suggestionsRec(root -> children[i], prefix);
prefix.pop_back();
}
}
}
int printAutoSuggestions(struct TrieNode *root, string query){
struct TrieNode* ptr = root;
for(int i = 0; i < query.length(); i++){
int index = charToIndex(query[i]);
if(!ptr -> children[index])
return 0;
ptr = ptr -> children[index];
}
bool isWord = (ptr -> isWordEnd == true);
bool isLast = isLastNode(ptr);
if(isWord and isLast){
cout << query << endl;
return -1;
}
if(!isLast){
string prefix = query;
suggestionsRec(ptr, query);
return 1;
}
}
int main()
{
struct TrieNode *root = getNode();
insert(root, "hello");
insert(root, "dog");
insert(root, "hell");
insert(root, "cat");
insert(root, "a");
insert(root, "hel");
insert(root, "help");
insert(root, "helps");
insert(root, "helping");
int comp = printAutoSuggestions(root, "hel");
if (comp == -1)
cout << "No other strings found with this prefix\n";
else if (comp == 0)
cout << "No string found with this prefix\n";
return 0;
}