Skip to content

Instantly share code, notes, and snippets.

@PrashantUnity
Created April 3, 2023 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PrashantUnity/810749d284b94fbce895362f58ed70bf to your computer and use it in GitHub Desktop.
Save PrashantUnity/810749d284b94fbce895362f58ed70bf to your computer and use it in GitHub Desktop.
Trie Data Structure
public class Node
{
public Dictionary<char,Node> value { get; set; } = new Dictionary<char,Node>();
public bool IsEndOfWord = false;
}
public class Trie
{
Node node;
public Trie()
{ node = new Node();}
public void Insert(string word)
{
var temp = node;
foreach(var i in word)
{
if(!temp.value.ContainsKey(i)) temp.value.Add(i,new Node());
temp = temp.value[i];
}
temp.IsEndOfWord=true;
}
public bool Search(string word) => SearchHelper(word,true);
public bool StartsWith(string prefix) => SearchHelper(prefix,false);
public bool SearchHelper(string word,bool search)
{
var temp = node;
foreach(var i in word)
{
if(!temp.value.ContainsKey(i)) return false;
temp = temp.value[i];
}
if(search) return temp.IsEndOfWord;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment