Skip to content

Commit a3133bc

Browse files
aQuaaQua
aQua
authored and
aQua
committed
accepted problem 49
1 parent 4bbc27c commit a3133bc

File tree

3 files changed

+57
-8
lines changed

3 files changed

+57
-8
lines changed

Algorithms/0049.group-anagrams/README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
# [49. Group Anagrams](https://leetcode.com/problems/group-anagrams/)
22

33
## 题目
4+
Given an array of strings, group anagrams together.
5+
```
6+
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
7+
Return:
48
5-
9+
[
10+
["ate", "eat","tea"],
11+
["nat","tan"],
12+
["bat"]
13+
]
14+
```
615
## 解题思路
716

817

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,38 @@
11
package Problem0049
22

3+
import (
4+
"sort"
5+
)
6+
7+
func groupAnagrams(strs []string) [][]string {
8+
res := [][]string{}
9+
record := make(map[string][]string)
10+
11+
for _, str := range strs {
12+
temp := sortString(str)
13+
record[temp] = append(record[temp], str)
14+
}
15+
for _, v := range record {
16+
sort.Strings(v)
17+
res = append(res, v)
18+
}
19+
20+
return res
21+
}
22+
23+
func sortString(s string) string {
24+
bytes := []byte(s)
25+
26+
temp := make([]int, len(bytes))
27+
for i, b := range bytes {
28+
temp[i] = int(b)
29+
}
30+
31+
sort.Ints(temp)
32+
33+
for i, v := range temp {
34+
bytes[i] = byte(v)
35+
}
36+
37+
return string(bytes)
38+
}
Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0049
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,13 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one []string
1919
}
2020

2121
// ans 是答案
2222
// one 代表第一个答案
2323
type ans struct {
24-
one string
24+
one [][]string
2525
}
2626

2727
func Test_Problem0049(t *testing.T) {
@@ -30,17 +30,21 @@ func Test_Problem0049(t *testing.T) {
3030
qs := []question{
3131

3232
question{
33-
para{""},
34-
ans{""},
33+
para{[]string{"eat", "tea", "tan", "ate", "nat", "bat"}},
34+
ans{[][]string{
35+
[]string{"ate", "eat", "tea"},
36+
[]string{"nat", "tan"},
37+
[]string{"bat"},
38+
}},
3539
},
36-
40+
3741
// 如需多个测试,可以复制上方元素。
3842
}
3943

4044
for _, q := range qs {
4145
a, p := q.ans, q.para
4246
fmt.Printf("~~%v~~\n", p)
4347

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
48+
ast.Equal(a.one, groupAnagrams(p.one), "输入:%v", p)
4549
}
4650
}

0 commit comments

Comments
 (0)