-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path49_group_anagrams_test.go
56 lines (49 loc) · 1.25 KB
/
49_group_anagrams_test.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
package main
import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/smartystreets/goconvey/convey"
"sort"
"testing"
)
// 字母异位词分组 https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked
func TestGroupAnagrams(t *testing.T) {
convey.Convey("字母异位词分组 ", t, func() {
testCase := []struct {
input []string
expected [][]string
}{
{
[]string{"eat", "tea", "tan", "ate", "nat", "bat"}, [][]string{
{"bat"},
{"nat", "tan"},
{"ate", "eat", "tea"},
},
},
{
[]string{}, [][]string{},
},
}
for _, tst := range testCase {
ret := groupAnagrams(tst.input)
convey.ShouldBeTrue(cmp.Equal(ret, tst.expected, cmpopts.SortSlices(func(x, y int) bool { return x < y })), true)
}
})
}
// 先按字母排序,排序后的字母为hash key
func groupAnagrams(strs []string) [][]string {
var keyMap = map[string][]string{}
for _, str := range strs {
s := []byte(str)
sort.Slice(s, func(i, j int) bool {
return s[i] < s[j]
})
sortedStr := string(s)
keyMap[sortedStr] = append(keyMap[sortedStr], str)
}
ans := make([][]string, 0, len(keyMap))
for _, v := range keyMap {
ans = append(ans, v)
}
return ans
}