MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / groupAnagrams1

Function groupAnagrams1

group_anagrams_49/solution.go:42–63  ·  view source on GitHub ↗

Second solution based on sorting the strings

(strs []string)

Source from the content-addressed store, hash-verified

40
41// Second solution based on sorting the strings
42func groupAnagrams1(strs []string) [][]string {
43 sorted := make([]string, len(strs))
44 for i := 0; i < len(strs); i++ {
45 sorted[i] = sortString(strs[i])
46 }
47
48 m := make(map[string][]string)
49 for i := 0; i < len(strs); i++ {
50 _, ok := m[sorted[i]]
51 if !ok {
52 m[sorted[i]] = []string{strs[i]}
53 } else {
54 m[sorted[i]] = append(m[sorted[i]], strs[i])
55 }
56 }
57
58 groups := make([][]string, 0)
59 for _, v := range m {
60 groups = append(groups, v)
61 }
62 return groups
63}
64
65func sortString(s string) string {
66 charArr := strings.Split(s, "")

Callers

nothing calls this directly

Calls 1

sortStringFunction · 0.85

Tested by

no test coverage detected