-
Notifications
You must be signed in to change notification settings - Fork 6
/
trie.go
68 lines (61 loc) · 1.15 KB
/
trie.go
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
package gochinadns
import (
"strings"
)
type domainTrie struct {
children map[string]*domainTrie
end bool
}
func (tr *domainTrie) Add(domain string) {
domain = strings.TrimSpace(domain)
if domain == "" {
return
}
domain = strings.Trim(domain, ".")
// "." contains all domains
if domain == "" {
tr.end = true
tr.children = nil
return
}
node := tr
labels := strings.Split(domain, ".")
for i := len(labels) - 1; i >= 0; i-- {
// domain is already contained in this trie.
if node.end {
return
}
if node.children == nil {
node.children = make(map[string]*domainTrie)
}
label := labels[i]
if node.children[label] == nil {
node.children[label] = new(domainTrie)
}
node = node.children[label]
}
node.end = true
}
func (tr *domainTrie) Contain(domain string) bool {
if tr == nil {
return false
}
domain = strings.Trim(domain, ".")
labels := strings.Split(domain, ".")
node := tr
if node.end {
return true
}
for i := len(labels) - 1; i >= 0; i-- {
label := labels[i]
node = node.children[label]
if node == nil {
return false
}
if node.end {
return true
}
}
// should not be here
return false
}