Skip to content

Commit 5d2b2a1

Browse files
committed
[Add LeetCode submission] - Group Anagrams (49) (golang)
1 parent 9d10c07 commit 5d2b2a1

File tree

2 files changed

+23
-18
lines changed

2 files changed

+23
-18
lines changed

Group Anagrams (49)/README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,19 @@ Medium
1818

1919
[solution.go](solution.go)
2020

21-
[LeetCode submissions section](https://leetcode.com/problems/group-anagrams/submissions/1615992382/)
21+
[LeetCode submissions section](https://leetcode.com/problems/group-anagrams/submissions/1616019720/)
2222

2323
### Performance
2424

25-
[LeetCode submission details](https://leetcode.com/submissions/detail/1615992382/)
25+
[LeetCode submission details](https://leetcode.com/submissions/detail/1616019720/)
2626

2727
#### CPU
2828

29-
Took 18 ms (beats 21.57%)
29+
Took 9 ms (beats 73.90%)
3030

3131
#### Memory
3232

33-
Used 10 MB (beats 41.11%)
33+
Used 9.5 MB (beats 72.15%)
3434

3535
## Problem statement
3636

Group Anagrams (49)/solution.go

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
11
func groupAnagrams(strs []string) [][]string {
2-
wordsMap := map[string][]string{}
2+
wordsMap := map[string]int{}
3+
res := [][]string{}
4+
cnt := 0
5+
for _, word := range strs {
6+
normalizedArr := []byte(word)
7+
sort.Slice(normalizedArr, func(i, j int) bool {
8+
return normalizedArr[i] < normalizedArr[j]
9+
})
10+
normalized := string(normalizedArr)
311

4-
for _, word := range strs {
5-
normalizedArr := strings.Split(word, "")
6-
sort.Strings(normalizedArr)
7-
normalized := strings.Join(normalizedArr, "")
12+
id, ok := wordsMap[normalized]
13+
if !ok {
14+
id = cnt
15+
wordsMap[normalized] = id
16+
res = append(res, []string{})
817

9-
anagrams := wordsMap[normalized]
10-
anagrams = append(anagrams, word)
11-
wordsMap[normalized] = anagrams
12-
}
18+
cnt++
19+
}
1320

14-
res := [][]string{}
15-
for _, list := range wordsMap {
16-
res = append(res, list)
17-
}
21+
res[id] = append(res[id], word)
22+
}
1823

19-
return res
24+
return res
2025
}

0 commit comments

Comments
 (0)