leetcode刷题笔记(Golang)--49. Group Anagrams

49. Group Anagrams

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.

golang没有找到对字符串进行排序API,在stackoverflow上面找到了一个实现

type sortRunes []rune

func groupAnagrams(strs []string) [][]string {
	res := [][]string{}
	gropMap := make(map[string][]string)
	for _, v := range strs {
		sortV := SortString(v)
		gropMap[sortV] = append(gropMap[sortV], v)
	}

	for _, v := range gropMap {
		res = append(res, v)
	}
	return res
}

func (s sortRunes) Less(i, j int) bool {
	return s[i] < s[j]
}

func (s sortRunes) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s sortRunes) Len() int {
	return len(s)
}

func SortString(s string) string {
	r := []rune(s)
	sort.Sort(sortRunes(r))
	return string(r)
}

你可能感兴趣的:(leetcode刷题笔记(Golang)--49. Group Anagrams)