题目
Implement a function all_anagram_groups() that,
given many input strings, will identify and group words that are anagrams of each other.
An anagram is word that is just a re-arrangement of the characters of another word,
like "reap" and "pear" and "a per" (whitespace is ignored).
But "pear" and "rep" are not, since "rep" does not have an "a".
Also, "the" and "thee" are not anagrams, because "the" only has one "e".
Given this example input:
[ "pear","dirty room","amleth","reap","tinsel","tesla","hamlet","dormitory","listen","silent" ]
The output should be an array-of-arrays (or list-of-lists)
[
["pear","reap"],
["dirty room","dormitory"],
["amleth","hamlet"],
["tinsel","listen","silent"],
["tesla"]
]
这个没有什么难点,顺序操作即可
leecode链接:https://leetcode.com/problems/group-anagrams/
type Item struct {
mp map[uint8]int
index int
}
func all_anagram_groups(input []string) [][]string {
var mps []*Item
for i := 0; i < len(input); i++ {
mp := make(map[uint8]int)
for j := 0; j < len(input[i]); j++ {
if input[i][j] == ' ' {
continue
}
mp[input[i][j]]++
}
mps = append(mps, &Item{
mp: mp,
index: i,
})
}
var groups [][]*Item
for i := 0; i < len(mps); i++ {
matched := false
for j := 0; j < len(groups); j++ {
if isMapEqual(mps[i].mp, groups[j][0].mp) {
groups[j] = append(groups[j], mps[i])
matched = true
break
}
}
if !matched {
groups = append(groups, []*Item{mps[i]})
}
}
var res [][]string
for _, group := range groups {
var tmp []string
for _, v := range group {
tmp = append(tmp, input[v.index])
}
res = append(res, tmp)
}
return res
}
func isMapEqual(mp1 map[uint8]int, mp2 map[uint8]int) bool {
if len(mp1) != len(mp2) {
return false
}
for k, v := range mp1 {
vv, ok := mp2[k]
if !ok {
return false
}
if vv != v {
return false
}
}
return true
}