-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.go
59 lines (57 loc) · 1.04 KB
/
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
type Trie struct {
children [26]*Trie
v [26]int
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(w string) {
node := this
t := w[len(w)-1] - 'a'
for _, c := range w {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
node.v[t]++
}
}
func (this *Trie) search(w string) string {
node := this
t := w[len(w)-1] - 'a'
res := &strings.Builder{}
for _, c := range w[:len(w)-1] {
res.WriteRune(c)
c -= 'a'
node = node.children[c]
if node.v[t] == 1 {
break
}
}
n := len(w) - res.Len() - 1
if n > 0 {
res.WriteString(strconv.Itoa(n))
}
res.WriteByte(w[len(w)-1])
if res.Len() < len(w) {
return res.String()
}
return w
}
func wordsAbbreviation(words []string) []string {
trees := map[int]*Trie{}
for _, w := range words {
if _, ok := trees[len(w)]; !ok {
trees[len(w)] = newTrie()
}
}
for _, w := range words {
trees[len(w)].insert(w)
}
ans := []string{}
for _, w := range words {
ans = append(ans, trees[len(w)].search(w))
}
return ans
}