using
System;
using
System.Collections.Generic;
public
class
GFG {
const
int
CHILD = 26;
class
TrieNode {
public
TrieNode[] children =
new
TrieNode[CHILD];
public
bool
isWordEnd;
}
static
string
ReverseStr(
string
str)
{
int
n = str.Length;
char
[] chars = str.ToCharArray();
for
(
int
i = 0; i < n / 2; i++) {
char
temp = chars[i];
chars[i] = chars[n - i - 1];
chars[n - i - 1] = temp;
}
return
new
string
(chars);
}
static
TrieNode GetNode()
{
TrieNode pNode =
new
TrieNode();
pNode.isWordEnd =
false
;
for
(
int
i = 0; i < CHILD; i++)
pNode.children[i] =
null
;
return
pNode;
}
static
void
Insert(TrieNode root,
string
key)
{
TrieNode pCrawl = root;
for
(
int
level = 0; level < key.Length; level++) {
int
index = key[level] -
'a'
;
if
(pCrawl.children[index] ==
null
)
pCrawl.children[index] = GetNode();
pCrawl = pCrawl.children[index];
}
pCrawl.isWordEnd =
true
;
}
static
bool
Search(TrieNode root,
string
key)
{
int
length = key.Length;
TrieNode pCrawl = root;
for
(
int
level = 0; level < length; level++) {
int
index = key[level] -
'a'
;
if
(pCrawl.children[index] ==
null
)
return
false
;
pCrawl = pCrawl.children[index];
}
return
(pCrawl !=
null
&& pCrawl.isWordEnd);
}
static
bool
IsLastNode(TrieNode root)
{
for
(
int
i = 0; i < CHILD; i++)
if
(root.children[i] !=
null
)
return
false
;
return
true
;
}
static
void
PrintStrings(TrieNode root,
string
currsuffix)
{
if
(root.isWordEnd) {
Console.WriteLine(ReverseStr(currsuffix));
currsuffix = ReverseStr(currsuffix);
}
if
(IsLastNode(root))
return
;
for
(
int
i = 0; i < CHILD; i++) {
if
(root.children[i] !=
null
) {
currsuffix += (
char
)(
'a'
+ i);
PrintStrings(root.children[i], currsuffix);
currsuffix = currsuffix.Substring(
0, currsuffix.Length - 1);
}
}
}
static
int
PrintStringsWithGivenSuffix(TrieNode root,
string
query)
{
TrieNode pCrawl = root;
int
level;
int
n = query.Length;
for
(level = 0; level < n; level++) {
int
index = query[level] -
'a'
;
if
(pCrawl.children[index] ==
null
)
return
0;
pCrawl = pCrawl.children[index];
}
bool
isWord = pCrawl.isWordEnd;
bool
isLast = IsLastNode(pCrawl);
if
(isWord && isLast) {
Console.WriteLine(query);
return
-1;
}
if
(!isLast) {
string
suffix = query;
PrintStrings(pCrawl, suffix);
return
1;
}
return
0;
}
static
void
Main(
string
[] args)
{
TrieNode root = GetNode();
List<
string
> S =
new
List<
string
>{
"geeks"
,
"geeksforgeeks"
,
"geek"
,
"newgeeks"
,
"friendsongeeks"
,
"toppergeek"
};
foreach
(
string
str
in
S)
{
Insert(root, ReverseStr(str));
}
string
P =
"eek"
;
PrintStringsWithGivenSuffix(root, ReverseStr(P));
}
}