-
Notifications
You must be signed in to change notification settings - Fork 496
/
Trie.cs
90 lines (76 loc) · 2.05 KB
/
Trie.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
class TrieNode
{
public char c;
public Dictionary<char, TrieNode> children;
public bool isWord;
public TrieNode()
{
children = new Dictionary<char, TrieNode>();
}
public TrieNode(char c)
{
this.c = c;
children = new Dictionary<char, TrieNode>();
}
}
public class Trie
{
private TrieNode root;
public Trie()
{
root = new TrieNode();
}
/// <summary>
/// Inserts a word into the Trie
/// Time Complexity: O(len(word))
/// </summary>
/// <param name="word">The word to insert</param>
public void Insert(String word)
{
TrieNode curr = root;
foreach (char c in word)
{
if (!curr.children.ContainsKey(c))
curr.children[c] = new TrieNode(c);
curr = curr.children[c];
}
curr.isWord = true;
}
/// <summary>
/// Searches the trie for a word
/// Time Complexity: O(len(word))
/// </summary>
/// <param name="word">The word to search for</param>
/// <returns>True if the word was found, false otherwise</returns>
public bool Search(String word)
{
TrieNode curr = root;
foreach (char c in word)
{
if (!curr.children.ContainsKey(c))
return false;
curr = curr.children[c];
}
return curr.isWord;
}
public static void Main()
{
Trie dictionary = new Trie();
// Input keys words
dictionary.Insert("the");
dictionary.Insert("a");
dictionary.Insert("there");
dictionary.Insert("answer");
dictionary.Insert("any");
dictionary.Insert("by");
dictionary.Insert("bye");
dictionary.Insert("their");
// Search for different keys words
Console.WriteLine(dictionary.Search("the"));
Console.WriteLine(dictionary.Search("these"));
Console.WriteLine(dictionary.Search("thaw"));
Console.WriteLine(dictionary.Search("their"));
}
}