Created
April 3, 2023 04:31
-
-
Save PrashantUnity/810749d284b94fbce895362f58ed70bf to your computer and use it in GitHub Desktop.
Trie Data Structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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