forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1408.go
46 lines (41 loc) · 910 Bytes
/
1408.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
func stringMatching(words []string) []string {
root := &Trie{}
for _, word := range words {
for i := 0; i < len(word); i++ {
root.Insert(word[i:len(word)])
}
}
res := []string{}
for _, word := range words {
if root.Get(word) {
res = append(res, word)
}
}
return res
}
type Trie struct {
val int
next [26]*Trie
}
func (this *Trie) Insert(word string) {
cur := this
for i := 0; i < len(word); i++ {
j := word[i] - 'a'
if cur.next[j] == nil {
cur.next[j] = &Trie{}
}
cur = cur.next[j]
cur.val++
}
}
func (this *Trie) Get(word string) bool {
cur := this
for i := 0; i < len(word); i++ {
j := word[i] - 'a'
if cur.next[j] == nil {
return false
}
cur = cur.next[j]
}
return cur.val > 1
}