...

/

Solution Review: Word Formation From a Vector Using a Trie

Solution Review: Word Formation From a Vector Using a Trie

Learn a detailed analysis of the different ways to solve the “Word Formation From a Vector Using a Trie” challenge.

Solution: Iterative word matching

Press + to interact
main.cs
Trie.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace chapter_7
{
class Program
{
static bool isFormationPossible(List<string> list, string word)
{
//Create Trie and insert vector elements in it
Trie trie = new Trie();
for (int x = 0; x < list.Count; x++)
{
trie.insertNode(list[x]);
}
TrieNode currentNode = trie.getRoot();
for (int i = 0; i < word.Length; i++)
{
char index = (Char)trie.getIndex(word[i]);
// if the prefix of word does not exist, word would not either
if (currentNode.children[index] == null)
{
return false;
}
// if the substring of the word exists as a word in trie, check whether rest of the word also exists, if it does return true
else if ((currentNode.children[index].isEndWord == true) && trie.searchNode(word.Substring(i + 1)))
{
return true;
}
currentNode = currentNode.children[index];
}
return false;
}
static void Main(string[] args)
{
List<string> keys = new List<string>{ "he", "hello", "loworld", "friend" };
if (isFormationPossible(keys, "helloworld"))
Console.WriteLine("true");
else
Console.WriteLine("false");
if (isFormationPossible(keys, "hellofriend"))
Console.WriteLine("true");
else
Console.WriteLine("false");
return;
}
}
}

The algorithm can be divided into three parts. The first and ...