forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
49 lines (46 loc) · 859 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
type trie struct {
children [26]*trie
isEnd bool
}
func (root *trie) insert(word string) {
node := root
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = &trie{}
}
node = node.children[c]
}
node.isEnd = true
}
func (root *trie) dfs(word string) bool {
if word == "" {
return true
}
node := root
for i, c := range word {
node = node.children[c-'a']
if node == nil {
return false
}
if node.isEnd && root.dfs(word[i+1:]) {
return true
}
}
return false
}
func findAllConcatenatedWordsInADict(words []string) (ans []string) {
sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
root := &trie{}
for _, word := range words {
if word == "" {
continue
}
if root.dfs(word) {
ans = append(ans, word)
} else {
root.insert(word)
}
}
return
}