-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
62 lines (59 loc) · 1020 Bytes
/
Solution.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
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func (this *Trie) search(word string) bool {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}
func longestWord(words []string) string {
sort.Slice(words, func(i, j int) bool {
a, b := words[i], words[j]
if len(a) != len(b) {
return len(a) < len(b)
}
return a > b
})
trie := newTrie()
var dfs func(string) bool
dfs = func(w string) bool {
if len(w) == 0 {
return true
}
for i := 1; i <= len(w); i++ {
if trie.search(w[:i]) && dfs(w[i:]) {
return true
}
}
return false
}
ans := ""
for _, w := range words {
if dfs(w) {
ans = w
}
trie.insert(w)
}
return ans
}