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.
已知一组字符串,将所有anagram(相同字符组成的字符串)放在一起输出。
解决方法:使用哈希表,以内部排序的各个单词为Key,字符串向量(vector<string>)为value,存储字符数量相同的字符串。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs)
{
vector<vector<string>> result;
map<string, vector<string>> logs;
for (auto str : strs)
{
string temp = str;
sort(temp.begin(), temp.end());
logs[temp].push_back(str);
}
for (auto log : logs)
{
vector<string> res = log.second;
result.push_back(res);
}
return result;
}
};