using
System;
using
System.Collections.Generic;
class
TrieNode
{
public
Dictionary<
char
, TrieNode> child;
public
bool
isLast;
public
TrieNode()
{
child =
new
Dictionary<
char
, TrieNode>();
for
(
char
i =
'a'
; i <=
'z'
; i++)
child.Add(i,
null
);
isLast =
false
;
}
}
class
Trie
{
public
TrieNode root;
public
void
insertIntoTrie(String []contacts)
{
root =
new
TrieNode();
int
n = contacts.Length;
for
(
int
i = 0; i < n; i++)
{
insert(contacts[i]);
}
}
public
void
insert(String s)
{
int
len = s.Length;
TrieNode itr = root;
for
(
int
i = 0; i < len; i++)
{
TrieNode nextNode = itr.child[s[i]];
if
(nextNode ==
null
)
{
nextNode =
new
TrieNode();
if
(itr.child.ContainsKey(s[i]))
itr.child[s[i]] = nextNode;
else
itr.child.Add(s[i], nextNode);
}
itr = nextNode;
if
(i == len - 1)
itr.isLast =
true
;
}
}
public
void
displayContactsUtil(TrieNode curNode,
String prefix)
{
if
(curNode.isLast)
Console.WriteLine(prefix);
for
(
char
i =
'a'
; i <=
'z'
; i++)
{
TrieNode nextNode = curNode.child[i];
if
(nextNode !=
null
)
{
displayContactsUtil(nextNode, prefix + i);
}
}
}
public
void
displayContacts(String str)
{
TrieNode prevNode = root;
String prefix =
""
;
int
len = str.Length;
int
i;
for
(i = 0; i < len; i++)
{
prefix += str[i];
char
lastChar = prefix[i];
TrieNode curNode = prevNode.child[lastChar];
if
(curNode ==
null
)
{
Console.WriteLine(
"\nNo Results Found for "
+ prefix);
i++;
break
;
}
Console.WriteLine(
"\nSuggestions based on "
+ prefix +
" are "
);
displayContactsUtil(curNode, prefix);
prevNode = curNode;
}
for
( ; i < len; i++)
{
prefix += str[i];
Console.WriteLine(
"\nNo Results Found for "
+ prefix);
}
}
}
public
class
GFG
{
public
static
void
Main(String []args)
{
Trie trie =
new
Trie();
String []contacts = {
"gforgeeks"
,
"geeksquiz"
};
trie.insertIntoTrie(contacts);
String query =
"gekk"
;
trie.displayContacts(query);
}
}