@@ -9,7 +9,7 @@ class Solution:
9
9
for s in strs:
10
10
sortedS = ' ' .join(sorted (s))
11
11
res[sortedS].append(s)
12
- return res.values()
12
+ return list ( res.values() )
13
13
```
14
14
15
15
``` java
@@ -85,6 +85,46 @@ public class Solution {
85
85
}
86
86
```
87
87
88
+ ``` go
89
+ func groupAnagrams (strs []string ) [][]string {
90
+ res := make (map [string ][]string )
91
+
92
+ for _ , s := range strs {
93
+ sortedS := sortString (s)
94
+ res[sortedS] = append (res[sortedS], s)
95
+ }
96
+
97
+ var result [][]string
98
+ for _ , group := range res {
99
+ result = append (result, group)
100
+ }
101
+ return result
102
+ }
103
+
104
+ func sortString (s string ) string {
105
+ characters := []rune (s)
106
+ sort.Slice (characters, func (i, j int ) bool {
107
+ return characters[i] < characters[j]
108
+ })
109
+ return string (characters)
110
+ }
111
+ ```
112
+
113
+ ``` kotlin
114
+ class Solution {
115
+ fun groupAnagrams (strs : Array <String >): List <List <String >> {
116
+ val res = mutableMapOf<String , MutableList <String >>()
117
+
118
+ for (s in strs) {
119
+ val sortedS = s.toCharArray().sorted().joinToString(" " )
120
+ res.getOrPut(sortedS) { mutableListOf () }.add(s)
121
+ }
122
+
123
+ return res.values.toList()
124
+ }
125
+ }
126
+ ```
127
+
88
128
:: tabs-end
89
129
90
130
### Time & Space Complexity
@@ -109,7 +149,7 @@ class Solution:
109
149
for c in s:
110
150
count[ ord(c) - ord('a')] += 1
111
151
res[ tuple(count)] .append(s)
112
- return res.values()
152
+ return list( res.values() )
113
153
```
114
154
115
155
```java
@@ -199,11 +239,49 @@ public class Solution {
199
239
}
200
240
```
201
241
242
+ ``` go
243
+ func groupAnagrams (strs []string ) [][]string {
244
+ res := make (map [[26 ]int ][]string )
245
+
246
+ for _ , s := range strs {
247
+ var count [26 ]int
248
+ for _ , c := range s {
249
+ count[c-' a' ]++
250
+ }
251
+ res[count] = append (res[count], s)
252
+ }
253
+
254
+ var result [][]string
255
+ for _ , group := range res {
256
+ result = append (result, group)
257
+ }
258
+ return result
259
+ }
260
+ ```
261
+
262
+ ``` kotlin
263
+ class Solution {
264
+ fun groupAnagrams (strs : Array <String >): List <List <String >> {
265
+ val res = HashMap <List <Int >, MutableList <String >>()
266
+
267
+ for (s in strs) {
268
+ val count = MutableList (26 ) { 0 }
269
+ for (c in s) {
270
+ count[c - ' a' ]++
271
+ }
272
+ res.getOrPut(count) { mutableListOf () }.add(s)
273
+ }
274
+
275
+ return res.values.toList()
276
+ }
277
+ }
278
+ ```
279
+
202
280
:: tabs-end
203
281
204
282
### Time & Space Complexity
205
283
206
284
* Time complexity: $O(m * n)$
207
285
* Space complexity: $O(m)$
208
286
209
- > Where $m$ is the number of strings and $n$ is the length of the longest string.
287
+ > Where $m$ is the number of strings and $n$ is the length of the longest string.
0 commit comments