Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
["ate", "eat","tea"] 排序的结果为 aet
["nat","tan"] 排序的结果为 atn
["bat"] 排序结果为 abt
放在一起的单词,排序相同,可以设置hash(string,vector<string>) 前面为排序后的单词,后面为相同的排序结果的单词。
取出每一个单词str: hash[alpha].push_back[str]即可。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> mp;//unordered_map内部不排序
vector<vector<string>> result;
int sz = strs.size();
for(int i=0;i<sz;++i){
string temp = strs[i];
sort(temp.begin(),temp.end());
mp[temp].push_back(strs[i]);//排序相同的放在同一个vector里面
}
for(auto iter_beg=mp.begin();iter_beg!=mp.end();++iter_beg){
result.push_back(iter_beg->second);
}
return result;
}
};