Created
September 12, 2024 20:46
-
-
Save vitor-mariano/64d366566f891cc7434a31fec8218f63 to your computer and use it in GitHub Desktop.
LeetCode 49 - Group Anagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
l := []string{"eat", "tea", "tan", "ate", "nat", "bat"} | |
fmt.Printf("%v\n", groupAnagrams(l)) | |
} | |
func groupAnagrams(l []string) (res [][]string) { | |
m := make(map[rune]int) | |
for _, a := range l { | |
gi := 0 | |
for _, r := range a { | |
i, ok := m[r] | |
if !ok { | |
i = len(res) | |
m[r] = i | |
} | |
if i > gi { | |
gi = i | |
} | |
} | |
if gi >= len(res) { | |
res = append(res, []string{a}) | |
} else { | |
res[gi] = append(res[gi], a) | |
} | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment