-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0049_Group_Anagrams.go
52 lines (45 loc) · 976 Bytes
/
0049_Group_Anagrams.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
package leetcode
import (
"sort"
"strings"
"sync"
)
func groupAnagrams(strs []string) [][]string {
groups := make(map[string][]string)
for _, str := range strs {
key := sortGroup(str)
groups[key] = append(groups[key], str)
}
result := make([][]string, 0, len(groups))
for _, group := range groups {
result = append(result, group)
}
return result
}
func sortGroup(s string) string {
// sort the string
spilt := strings.Split(s, "")
sort.Strings(spilt)
return strings.Join(spilt, "")
}
func groupAnagrams2(strs []string) [][]string {
groups := make(map[string][]string)
var wg sync.WaitGroup
var mutex = &sync.Mutex{}
for _, str := range strs {
wg.Add(1)
go func(s string) {
defer wg.Done()
key := sortGroup(s)
mutex.Lock()
groups[key] = append(groups[key], s)
mutex.Unlock()
}(str)
}
wg.Wait()
result := make([][]string, 0, len(groups))
for _, group := range groups {
result = append(result, group)
}
return result
}