-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.cs
101 lines (82 loc) · 1.65 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
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
/**
* A space-saving data structure to store words and their counts.
* Words that share prefixes will have common paths along a branch of the tree.
*/
public class Trie
{
private TrieNode head;
public Trie ()
{
head = new TrieNode();
}
/**
* Add a word to the trie.
* Adding is O (|A| * |W|), where A is the alphabet and W is the word being searched.
*/
public void AddWord(string word)
{
TrieNode curr = head;
curr = curr.GetChild (word [0], true);
for (int i = 1; i < word.Length; i++)
{
curr = curr.GetChild (word [i], true);
}
curr.AddCount ();
}
/**
* Get the count of a partictlar word.
* Retrieval is O (|A| * |W|), where A is the alphabet and W is the word being searched.
*/
public int GetCount(string word)
{
TrieNode curr = head;
foreach (char c in word)
{
curr = curr.GetChild (c);
if (curr == null)
{
return 0;
}
}
return curr.count;
}
internal class TrieNode
{
private LinkedList<TrieNode> children;
public int count { private set; get; }
public char data { private set; get; }
public TrieNode(char data = ' ')
{
this.data = data;
count = 0;
children = new LinkedList<TrieNode>();
}
public TrieNode GetChild(char c, bool createIfNotExist = false)
{
foreach (var child in children)
{
if (child.data == c)
{
return child;
}
}
if (createIfNotExist)
{
return CreateChild (c);
}
return null;
}
public void AddCount()
{
count++;
}
public TrieNode CreateChild(char c)
{
var child = new TrieNode (c);
children.AddLast (child);
return child;
}
}
}