Add project files.
This commit is contained in:
66
Core.Blueprint.Storage/Adapters/Trie/TrieNode.cs
Normal file
66
Core.Blueprint.Storage/Adapters/Trie/TrieNode.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
|
||||
namespace Core.Blueprint.Storage
|
||||
{
|
||||
public class TrieNode
|
||||
{
|
||||
public Dictionary<char, TrieNode> Children { get; private set; }
|
||||
public bool IsEndOfWord { get; set; }
|
||||
|
||||
public TrieNode()
|
||||
{
|
||||
Children = [];
|
||||
IsEndOfWord = false;
|
||||
}
|
||||
}
|
||||
public class Trie
|
||||
{
|
||||
private readonly TrieNode _root;
|
||||
|
||||
public Trie()
|
||||
{
|
||||
_root = new TrieNode();
|
||||
}
|
||||
|
||||
public void Insert(string word)
|
||||
{
|
||||
var node = _root;
|
||||
foreach (var ch in word)
|
||||
{
|
||||
if (!node.Children.ContainsKey(ch))
|
||||
{
|
||||
node.Children[ch] = new TrieNode();
|
||||
}
|
||||
node = node.Children[ch];
|
||||
}
|
||||
node.IsEndOfWord = true;
|
||||
}
|
||||
|
||||
public List<string> SearchByPrefix(string? prefix)
|
||||
{
|
||||
var results = new List<string>();
|
||||
var node = _root;
|
||||
foreach (var ch in prefix)
|
||||
{
|
||||
if (!node.Children.ContainsKey(ch))
|
||||
{
|
||||
return results;
|
||||
}
|
||||
node = node.Children[ch];
|
||||
}
|
||||
SearchByPrefixHelper(node, prefix, results);
|
||||
return results;
|
||||
}
|
||||
|
||||
private void SearchByPrefixHelper(TrieNode node, string currentPrefix, List<string> results)
|
||||
{
|
||||
if (node.IsEndOfWord)
|
||||
{
|
||||
results.Add(currentPrefix);
|
||||
}
|
||||
foreach (var kvp in node.Children)
|
||||
{
|
||||
SearchByPrefixHelper(kvp.Value, currentPrefix + kvp.Key, results);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user