using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
bool
canbuildword(
string
s,
bool
isoriginalword,
Dictionary<
string
,
bool
> mp)
{
if
(mp.ContainsKey(s) && !mp[s])
return
false
;
if
(mp.ContainsKey(s) && mp[s] && !isoriginalword) {
return
true
;
}
for
(
int
i = 1; i < s.Length; i++) {
string
left = s.Substring(0, i);
string
right = s.Substring(i);
if
(mp.ContainsKey(left) && mp[left]
&& canbuildword(right,
false
, mp)) {
return
true
;
}
}
mp[s] =
false
;
return
false
;
}
public
static
string
printlongestword(
string
[] listofwords)
{
Dictionary<
string
,
bool
> mp
=
new
Dictionary<
string
,
bool
>();
foreach
(
string
s
in
listofwords) {
mp[s] =
true
;
}
Array.Sort(listofwords,
(a, b) => b.Length - a.Length);
foreach
(
string
s
in
listofwords) {
if
(canbuildword(s,
true
, mp))
return
s;
}
return
"-1"
;
}
static
public
void
Main()
{
string
[] listofwords = {
"geeks"
,
"for"
,
"geeksfor"
,
"geeksforgeeks"
};
Console.WriteLine(printlongestword(listofwords));
}
}