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.
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
①C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
map<map<char, int>, vector<string>> Hash;//用map当作map的键
for(int i = 0; i < strs.size(); i++){
map<char, int> temp;
for(auto x : strs[i]){
temp[x]++;
}
Hash[temp].push_back(strs[i]);
}
for(auto it = Hash.begin(); it!=Hash.end(); it++){
res.push_back(it->second);
}
return res;
}
};
②C++ 改良版
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> Hash;
for(auto x : strs){
string t = x;
sort(t.begin(), t.end());//用Hash表前先sort字符串,这样就不需要用到2层map的嵌套
Hash[t].push_back(x);
}
for(auto it : Hash){
res.push_back(it.second);
}
return res;
}
};