-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphone_directory.cpp
More file actions
97 lines (81 loc) · 1.79 KB
/
Copy pathphone_directory.cpp
File metadata and controls
97 lines (81 loc) · 1.79 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
#include<bits/stdc++.h>
#include<map>
using namespace std;
struct trie{
map<char, struct trie*>child;
int isleaf;
trie(){
char i;
for(i='a';i<='z';i++){
child[i]=NULL;
}
isleaf=0;
}
};
struct trie *root= NULL;
void insert(string s){
int len = s.length();
struct trie *itr=root;
int i;
for(i=0;i<len;i++){
struct trie *nextnode = itr->child[s[i]];
if(nextnode==NULL){
nextnode= new trie();
itr->child[s[i]]=nextnode;
}
itr=nextnode;
if(i==len-1){
itr->isleaf=1;
}
}
}
void displayContactsUtil(struct trie *curNode, string prefix)
{
if (curNode->isleaf)
cout << prefix << endl;
for (char i = 'a'; i <= 'z'; i++)
{
struct trie *nextNode = curNode->child[i];
if (nextNode != NULL)
displayContactsUtil(nextNode, prefix + (char)i);
}
}
void displaycontacts(string str){
struct trie *prevnode = root;
string prefix="";
int len = str.length();
int i;
for(i=0;i<len;i++){
prefix+=(char)str[i];
char lastchar = prefix[i];
struct trie *currnode = prevnode->child[lastchar];
if(currnode==NULL){
cout<<"no results found for "<<prefix<<"\n";
i++;
break;
}
cout<<"suggestions based on "<<prefix<<"\n";
displayContactsUtil(currnode, prefix);
prevnode=currnode;
}
}
void insertIntoTrie(string contacts[],int n)
{
// Initialize root Node
root = new trie();
// Insert each contact into the trie
for (int i = 0; i < n; i++)
insert(contacts[i]);
}
int main()
{
// Contact list of the User
string contacts[] = {"nitin" , "nitish", "nitesh"};
// Size of the Contact List
int n = sizeof(contacts)/sizeof(string);
// Insert all the Contacts into Trie
insertIntoTrie(contacts, n);
string query = "nikant";
displaycontacts(query);
return 0;
}