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
// @Title: 添加与搜索单词 - 数据结构设计 (Design Add and Search Words Data Structure)
// @Author: 15816537946@163.com
// @Date: 2021-10-19 16:14:08
// @Runtime: 56 ms
// @Memory: 14.2 MB
type WordDictionary struct {
	head *tireNode
}

type tireNode struct {
	child []*tireNode

	end bool
}

func Constructor() WordDictionary {
	dict := WordDictionary{}
	dict.head = NewTireNode()
	return dict
}

func NewTireNode() *tireNode {
	node := tireNode{}
	node.child = make([]*tireNode, 26)
	node.end = false
	return &node
}

func (this *WordDictionary) AddWord(word string) {
	node := this.head
	for _, v := range word {
		if node.child[v-'a'] == nil {
			node.child[v-'a'] = NewTireNode()
		}

		node = node.child[v-'a']
	}

	node.end = true
}

func (this *WordDictionary) Search(word string) bool {
	return this.head.search(word)
}

// search method with DFS
func (this *tireNode) search(word string) bool {
	// DFS finish, true if precise end-node
	if len(word) == 0 {
		return this.end
	}

	// case '.', DFS all child
	if word[0] == '.' {
		for _, v := range this.child {
			if v != nil && v.search(word[1:]) {
				return true
			}
		}
		// case others: DFS if exist
	} else {
		return this.child[word[0]-'a'] != nil && this.child[word[0]-'a'].search(word[1:])
	}
	return false

}