-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrieAutoSuggestion.cpp
More file actions
76 lines (73 loc) · 2.23 KB
/
trieAutoSuggestion.cpp
File metadata and controls
76 lines (73 loc) · 2.23 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
#ifndef TRIE_AUTO // Include guard
#define TRIE_AUTO
// Trie dataStructure for Auto-Suggestions(Prefix Tree)
#include<bits/stdc++.h>
using namespace std;
class TrieNode{
public:
bool isComplete=false;// to know that a particular word is completed or not
unordered_map<char, TrieNode*> child;// to know that what is the following letter after this letter;
//this is the modified trie node as the text may contain any character
};
class Trie{
public:
TrieNode* root;
Trie()
{
root=new TrieNode();
}
void insert(string &wordToInsert)
{
TrieNode* node = root;
for (auto &ch : wordToInsert) {
ch = tolower(ch); // Converting the character to lower case
if (node->child.find(ch) == node->child.end()) {
node->child[ch] = new TrieNode();
}
node = node->child[ch];
}
node->isComplete = true; // Mark the end of the word
}
void allWordsWithPrefixHelper(string &prefix, TrieNode* node, vector<string> &allWords)
{
if (node->isComplete) {
allWords.push_back(prefix);
}
for (auto &it : node->child) {
prefix.push_back(it.first);
allWordsWithPrefixHelper(prefix, it.second, allWords);
prefix.pop_back();
}
}
vector<string> allWordsWithPrefixFinder(string &prefix)
{
vector<string> allWords;
TrieNode* node = root;
for(auto it:node->child)cout<<it.first<<" ";
for (auto &ch : prefix) {
ch = tolower(ch); // Converting the character to lower case
if (node->child.find(ch) == node->child.end()) {
cout<<"No words with this prefix"<<endl;
return allWords;
}
node = node->child[ch];
}
allWordsWithPrefixHelper(prefix, node, allWords);
return allWords;
}
}rootBase;
void insertIntoTrie(vector<string> &words)
{
for(auto &it: words)
{
rootBase.insert(it);
}
return;
}
vector<string> allWordsWithPrefix(string &prefix)
{
cout<<"call received for"<<prefix<<endl;
return rootBase.allWordsWithPrefixFinder(prefix);
}
// Time Complexity: O(N) where N is the length of the word
#endif