1 题目
Given an array of strings, group anagrams together.
2 尝试解
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string,vector<string>> dic;
for(int i = 0; i < strs.size(); i++){
string temp = strs[i];
sort(temp.begin(),temp.end());
if(dic.count(temp) == 0){
vector<string> temp_set;
temp_set.push_back(strs[i]);
dic[temp] = temp_set;
}
else{
dic[temp].push_back(strs[i]);
}
}
map<string,vector<string>>::iterator item;
item = dic.begin();
vector<vector<string>> result;
while(item != dic.end()){
result.push_back(item->second);
item++;
}
return result;
}
};
3 标准解
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (string s : strs) {
string t = s;
sort(t.begin(), t.end());
mp[t].push_back(s);
}
vector<vector<string>> anagrams;
for (auto p : mp) {
anagrams.push_back(p.second);
}
return anagrams;
}
};