## 题目地址

https://leetcode.com/problems/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.

## 思路

``````class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
string t = str;
sort(t.begin(), t.end());
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};

``````

``````class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
vector<int> cnt(26);
string t;
for (char c : str) ++cnt[c - 'a'];
for (int d : cnt) t += to_string(d) + "/";
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};
``````

### 思路 2

``````var groupAnagrams = function(strs) {
const hashTable = {};

function sort(str) {
return str
.split("")
.sort()
.join("");
}

// 这个方法需要排序，因此不是很优，但是很直观，容易想到
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
const key = sort(str);
if (!hashTable[key]) {
hashTable[key] = [str];
} else {
hashTable[key].push(str);
}
}

return Object.values(hashTable);
};
``````

• 桶排序

## 代码

• 语言支持： JavaScript，Python3
``````/*
* @lc app=leetcode id=49 lang=javascript
*
* [49] Group Anagrams
*/
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
// 类似桶排序

let counts = [];
const hashTable = {};
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
counts = Array(26).fill(0);
for (let j = 0; j < str.length; j++) {
counts[str[j].charCodeAt(0) - "a".charCodeAt(0)]++;
}
const key = counts.join("");
if (!hashTable[key]) {
hashTable[key] = [str];
} else {
hashTable[key].push(str);
}
}

return Object.values(hashTable);
};
``````

Python3 Code:

``````class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""
思路同上，在Python中，这里涉及到3个知识点：
1. 使用内置的 defaultdict 字典设置默认值；
2. 内置的 ord 函数，计算ASCII值（等于chr）或Unicode值(等于unichr)；
3. 列表不可哈希，不能作为字典的键，因此这里转为元组；
"""
str_dict = collections.defaultdict(list)
for s in strs:
s_key = [0] * 26
for c in s:
s_key[ord(c)-ord('a')] += 1
str_dict[tuple(s_key)].append(s)
return str_dict.values()
``````

评论
0 评论