1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// @Title: 字母异位词分组 (Group Anagrams)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 452 ms
// @Memory: 73.2 MB
/*
 * @lc app=leetcode.cn id=49 lang=golang
 *
 * [49] 字母异位词分组
 *
 * https://leetcode-cn.com/problems/group-anagrams/description/
 *
 * algorithms
 * Medium (58.42%)
 * Likes:    183
 * Dislikes: 0
 * Total Accepted:    28.1K
 * Total Submissions: 47.9K
 * Testcase Example:  '["eat","tea","tan","ate","nat","bat"]'
 *
 * 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
 *
 * 示例:
 *
 * 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
 * 输出:
 * [
 * ⁠ ["ate","eat","tea"],
 * ⁠ ["nat","tan"],
 * ⁠ ["bat"]
 * ]
 *
 * 说明:
 *
 *
 * 所有输入均为小写字母。
 * 不考虑答案输出的顺序。
 *
 *
 */
func groupAnagrams(strs []string) [][]string {
	if len(strs) == 0 {
		return nil
	}

	tmp := make(map[int][]string )
	for _, s := range strs {
		c := encode(s)
		tmp[c] = append(tmp[c], s)
	}

	res := make([][]string, 0, len(tmp))
	for _,v := range tmp {
		res = append(res, v)
	}
	return res

}

var prime =  []int{5, 71, 37, 29, 2, 53, 59, 19, 11, 83, 79, 31, 43, 13, 7, 67, 97, 23, 17, 3, 41, 73, 47, 89, 61, 101}
func encode(s string) int {
	res := 1
	for i := range s {
		res *= prime[s[i] - 'a']
	}
	return res
}