# 49. Group Anagrams 字母异位词分组

@TOC

## # 题目描述

Given an array of strings, group anagrams together.

Example:

``````Input: ["eat", "tea", "tan", "ate", "nat", "bat"],

Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
``````

Note:

1. All inputs will be in lowercase.
2. The order of your output does not matter.

## # 解题方法

### # 排序+hash

``````public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
List<List<String>> ans = new ArrayList<List<String>>();
return ans;
}
HashMap<String, List<String>> hash = new HashMap<String, List<String>>();
for (String s : strs) {
char ca[] = s.toCharArray();
Arrays.sort(ca);
String temp = String.valueOf(ca);
if (!hash.containsKey(temp)) {
List<String> vals = new ArrayList<String>();
hash.put(temp, vals);
} else {
}
}
List<List<String>> ans = new ArrayList<List<String>>();
return ans;
}
}
``````

``````class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
res = collections.defaultdict(list)
for string in strs:
sorted_str = ''.join(sorted(string))
res[sorted_str].append(string)
return res.values()
``````

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

## # 日期

2017 年 4 月 9 日 2018 年 3 月 21 日 2019 年 1 月 2 日 —— 2019年开刷