-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution211.cs
78 lines (71 loc) · 2.16 KB
/
Solution211.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
namespace LeetCode.Solutions;
public class Solution211
{
/// <summary>
/// 211. Design Add and Search Words Data Structure - Medium
/// <a href="https://leetcode.com/problems/design-add-and-search-words-data-structure">See the problem</a>
/// </summary>
public class WordDictionary
{
private readonly TrieNode _root;
public WordDictionary()
{
_root = new TrieNode();
}
public void AddWord(string word)
{
var node = _root;
foreach (var c in word)
{
if (!node.Children.ContainsKey(c))
{
node.Children[c] = new TrieNode();
}
node = node.Children[c];
}
node.IsEnd = true;
}
public bool Search(string word)
{
return Search(word, _root);
}
private bool Search(string word, TrieNode node)
{
for (var i = 0; i < word.Length; i++)
{
var c = word[i];
if (c == '.')
{
foreach (var child in node.Children.Values)
{
if (Search(word[(i + 1)..], child))
{
return true;
}
}
return false;
}
if (!node.Children.ContainsKey(c))
{
return false;
}
node = node.Children[c];
}
return node.IsEnd;
}
/// <summary>
/// Trie node, which contains children nodes and a flag to indicate the end of a word.
/// </summary>
private class TrieNode
{
/// <summary>
/// Children nodes. The key is a character, and the value is a trie node.
/// </summary>
public Dictionary<char, TrieNode> Children { get; } = [];
/// <summary>
/// Indicates the end of a word.
/// </summary>
public bool IsEnd { get; set; }
}
}
}