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
// @Title: 词典中最长的单词 (Longest Word in Dictionary)
// @Author: 15816537946@163.com
// @Date: 2022-03-17 16:31:36
// @Runtime: 16 ms
// @Memory: 7.1 MB


type Trie struct {
	children [26]*Trie
	isEnd    bool
}

func (t *Trie) Insert(word string) {
	node := t
	for _, w := range word {
		w -= 'a'
		if node.children[w] == nil {
			node.children[w] = &Trie{}
		}
		node = node.children[w]
	}
	node.isEnd = true
}

func (t *Trie) Search(word string) bool {
	node := t
	for _, w := range word {
		w -= 'a'
		if node.children[w] == nil || !node.children[w].isEnd {
			return false
		}
		node = node.children[w]
	}
	return true
}

func longestWord(words []string) string {
	t := &Trie{}
	for _, w := range words {
		t.Insert(w)
	}

	var ret string
	for _, w := range words {
		if t.Search(w) && (len(w) > len(ret) || len(w) == len(ret) && w < ret) {
			ret = w
		}
	}
	return ret

}