-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathphrase_tree.go
66 lines (55 loc) · 1.77 KB
/
phrase_tree.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
package libgochewing
type PhraseTree struct {
root *PhraseTreeNode
}
type PhraseTreeNode struct {
children map[uint16]*PhraseTreeNode
phraseArrayItem []*PhraseArrayItem
}
func newPhraseTree() (phraseTree *PhraseTree) {
phraseTree = new(PhraseTree)
phraseTree.root = newPhraseTreeNode()
return phraseTree
}
func newPhraseTreeNode() (phraseTreeNode *PhraseTreeNode) {
phraseTreeNode = new(PhraseTreeNode)
phraseTreeNode.children = make(map[uint16]*PhraseTreeNode)
return phraseTreeNode
}
func (this *PhraseTree) insert(phraseArrayItem *PhraseArrayItem) {
current := this.root
for _, phone := range phraseArrayItem.phoneSeq {
phone = getFuzzyPhone(phone, PHONE_FUZZY_ALL)
if current.children[phone] == nil {
current.children[phone] = newPhraseTreeNode()
}
current = current.children[phone]
}
current.insert(phraseArrayItem)
}
func (this *PhraseTreeNode) insert(phraseArrayItem *PhraseArrayItem) {
if this.phraseArrayItem == nil {
this.phraseArrayItem = make([]*PhraseArrayItem, 0, 1)
}
this.phraseArrayItem = append(this.phraseArrayItem, phraseArrayItem)
}
func (this *PhraseTree) query(phoneSeq []uint16, flag uint32) []*PhraseArrayItem {
current := this.root
for _, phone := range phoneSeq {
phone = getFuzzyPhone(phone, PHONE_FUZZY_ALL)
if current.children[phone] == nil {
return make([]*PhraseArrayItem, 0)
}
current = current.children[phone]
}
return current.query(phoneSeq, flag)
}
func (this *PhraseTreeNode) query(phoneSeq []uint16, flag uint32) (phraseArrayItem []*PhraseArrayItem) {
phraseArrayItem = make([]*PhraseArrayItem, 0, len(this.phraseArrayItem))
for _, item := range this.phraseArrayItem {
if comparePhoneSeq(phoneSeq, item.phoneSeq, flag) == 0 {
phraseArrayItem = append(phraseArrayItem, item)
}
}
return phraseArrayItem
}