forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0208-ImplementTrie.cs
69 lines (56 loc) · 1.9 KB
/
0208-ImplementTrie.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
//-----------------------------------------------------------------------------
// Runtime: 184ms
// Memory Usage: 48 MB
// Link: https://leetcode.com/submissions/detail/263024765/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0208_ImplementTrie
{
private Node root;
/** Initialize your data structure here. */
public _0208_ImplementTrie()
{
root = new Node();
}
/** Inserts a word into the trie. */
public void Insert(string word)
{
var currentNode = root;
foreach (var ch in word)
{
if (currentNode.Children[ch - 'a'] == null)
currentNode.Children[ch - 'a'] = new Node();
currentNode = currentNode.Children[ch - 'a'];
}
currentNode.IsFinished = true;
}
/** Returns if the word is in the trie. */
public bool Search(string word)
{
var currentNode = root;
foreach (var ch in word)
if (currentNode.Children[ch - 'a'] == null)
return false;
else
currentNode = currentNode.Children[ch - 'a'];
return currentNode.IsFinished;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public bool StartsWith(string prefix)
{
var currentNode = root;
foreach (var ch in prefix)
if (currentNode.Children[ch - 'a'] == null)
return false;
else
currentNode = currentNode.Children[ch - 'a'];
return true;
}
public class Node
{
public Node[] Children { get; } = new Node[26];
public bool IsFinished { get; set; }
}
}
}