forked from unruledboy/SharpWordFinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordNode.cs
46 lines (42 loc) · 1.3 KB
/
WordNode.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
using System.Collections.Generic;
namespace Xnlab.WordSearch
{
public class WordNode
{
public bool IsWord { get; set; }
public char Current { get; }
public Dictionary<char, WordNode> Children { get; }
public WordNode(char c)
{
Children = new Dictionary<char, WordNode>();
Current = c;
}
public void Add(string word, int index = 0)
{
if (word.Length == index + 1)
IsWord = true;
else
{
var next = word[index + 1];
WordNode child;
if (!Children.TryGetValue(next, out child))
Children[next] = new WordNode(next);
else if (Children[next].Children.Count == 0)
Children[next] = new WordNode(next) { IsWord = true };
Children[next].Add(word, index + 1);
}
}
internal void Visit(WordCharacters chars, List<string> results)
{
if (chars.Take(Current))
{
if (IsWord)
results.Add(chars.Word);
foreach (var child in Children.Values)
{
child.Visit(chars.Clone(), results);
}
}
}
}
}