67 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			67 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| 
 | |
| 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);
 | |
|             }
 | |
|         }
 | |
|     }
 | |
| }
 | 
