题目描述
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
思路:
- 以排序后单词为键,加入哈希表。遍历哈希打印
细节:
- 实现接口以调用sort.Sort()
- 哈希表put直接用append,避免判断是否存在,和初始化[]string的值类型。
解:
package main
import "sort"
func groupAnagrams(strs []string) [][]string {
var hashmap map[string][]string
hashmap = make(map[string][]string)
for _,elem := range strs {
elemSorted := stringSort(elem)
//use append to avoid "contains()" and make()
hashmap[elemSorted] = append(hashmap[elemSorted],elem)
}
var res [][]string
for _,value := range hashmap {
res = append(res,value)
}
return res
}
//go用sort内置包实现字串排序的方法
func stringSort(s string) string {
sArr := []rune(s)
sort.Sort(RuneSlice(sArr))
return string(sArr)
}
type RuneSlice []rune
func (rs RuneSlice)Len() int {
return len(rs)
}
func (rs RuneSlice)Less(i,j int) bool {
return rs[i] < rs[j]
}
func (rs RuneSlice)Swap(i,j int) {
rs[i],rs[j] = rs[j],rs[i]
}
网友评论