forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.cs
80 lines (70 loc) · 1.79 KB
/
0211-design-add-and-search-words-data-structure.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
public class TrieNode
{
public Dictionary<char, TrieNode> Children;
public bool EndOfWord;
public TrieNode()
{
Children = new Dictionary<char, TrieNode>();
EndOfWord = false;
}
}
public class WordDictionary
{
public TrieNode root;
public WordDictionary()
{
root = new TrieNode();
}
public void AddWord(string word)
{
var current = root;
for (var i = 0; i < word.Length; i++)
{
if (!current.Children.ContainsKey(word[i]))
{
var newNode = new TrieNode();
current.Children.Add(word[i], newNode);
}
current = current.Children[word[i]];
}
current.EndOfWord = true;
}
public bool Search(string word)
{
return dfs(0, root, word);
}
private bool dfs(int index, TrieNode root, string word)
{
var currentNode = root;
for (var i = index; i < word.Length; i++)
{
var letter = word[i];
if (letter == '.')
{
foreach (var (key, value) in currentNode.Children)
{
if (dfs(i + 1, value, word))
{
return true;
}
}
return false;
}
else
{
if (!currentNode.Children.ContainsKey(letter))
{
return false;
}
currentNode = currentNode.Children[letter];
}
}
return currentNode.EndOfWord;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.AddWord(word);
* bool param_2 = obj.Search(word);
*/