Given the following lines
"Alberry K2503 F40 D",
"Alberry K2503 F40 S",
"Demi Deco Denver BLK",
"Demi Deco Denver BRN",
"Demi Deco Tank",
"Demi Deco Audi",
"Samsung S 19 S10",
"Samsung S 19 S12"
I need to get a list with the following
Alberry K2503 F40
Demi Deco Denver
Demi Deco
Samsung S 19
I tried to implement it in such way.
class TrieNode
{
public string Word { get; set; }
public TrieNode Parent { get; set; }
public Dictionary<string, TrieNode> Children { get; set; } = new Dictionary<string, TrieNode>();
public override string ToString()
{
return $"{Word}";
}
}
class Program
{
static string JoinSentence(TrieNode node)
{
List<string> sentence = new List<string>();
while (node != null)
{
sentence.Insert(0, node.Word);
node = node.Parent;
}
return string.Join(" ", sentence);
}
static void GetSentences(TrieNode node, HashSet<string> sentences)
{
if (node.Children.Count > 0)
{
foreach (var nodeChild in node.Children)
{
GetSentences(nodeChild.Value, sentences);
}
}
else
{
if (node.Parent.Children.Count == 1)
{
sentences.Add(JoinSentence(node));
}
else
{
bool lastChildren = false;
foreach (var child in node.Parent.Children)
{
if (child.Value != node)
{
if (child.Value.Children.Count > 0)
{
lastChildren = true;
sentences.Add(JoinSentence(node));
break;
}
}
}
if (!lastChildren)
{
sentences.Add(JoinSentence(node.Parent));
}
}
}
}
static void Main(string[] args)
{
var root = new TrieNode();
var sentences = new[]
{
"Alberry K2503 F40 D",
"Alberry K2503 F40 S",
"Demi Deco Denver BLK",
"Demi Deco Denver BRN",
"Demi Deco Tank",
"Demi Deco Audi",
"Samsung S 19 S10",
"Samsung S 19 S12"
};
foreach (var sentence in sentences)
{
var words = sentence.Split(' ');
TrieNode node = null;
foreach (var word in words)
{
if (node == null)
{
if (root.Children.ContainsKey(word))
{
node = root.Children[word];
}
else
{
node = new TrieNode {Word = word, Parent = root};
root.Children.Add(word, node);
}
}
else
{
if (node.Children.ContainsKey(word))
{
node = node.Children[word];
}
else
{
node.Children.Add(word, node = new TrieNode {Word = word, Parent = node});
}
}
}
}
var sentencesCommon = new HashSet<string>();
GetSentences(root, sentencesCommon);
foreach (var sentence in sentencesCommon)
{
Debug.WriteLine(sentence);
}
}
}
it seems to work, but is missing the result Demi Deco
where Audi
and Tank
shall be omitted.
I think I really messed with traversing the tree properly and getting unique sentences. Looks like I'm reinventing the wheel. Would someone recommend a better solution?
Thx