-
Notifications
You must be signed in to change notification settings - Fork 0
/
L720.go
71 lines (62 loc) · 1.36 KB
/
L720.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
69
70
71
package main
import (
"fmt"
"sort"
)
func main() {
res2 := longestWord2([]string{"a", "banana", "app", "appl", "ap", "apply", "apple"})
res := longestWord([]string{"a", "banana", "app", "appl", "ap", "apply", "apple"})
fmt.Println(res, res2)
}
func longestWord(words []string) string {
var res string
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j]) || len(words[i]) == len(words[j]) && words[i] > words[j]
})
mem := map[string]string{"": "ok"}
for _, word := range words {
if _, ok := mem[word[:len(word)-1]]; ok {
res = word
mem[word] = "ok"
}
}
return res
}
type Trie struct {
children [26]*Trie
isEnd bool
}
func (t *Trie) Insert(word string) {
node := t
for _, ch := range word {
ch -= 'a'
if node.children[ch] == nil {
node.children[ch] = &Trie{}
}
node = node.children[ch]
}
node.isEnd = true
}
func (t *Trie) Search(word string) bool {
node := t
for _, ch := range word {
ch -= 'a'
if node.children[ch] == nil || !node.children[ch].isEnd {
return false
}
node = node.children[ch]
}
return true
}
func longestWord2(words []string) (longest string) {
t := &Trie{}
for _, word := range words {
t.Insert(word)
}
for _, word := range words {
if t.Search(word) && (len(word) > len(longest) || len(word) == len(longest) && word < longest) {
longest = word
}
}
return longest
}