题目:
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
if(strs.empty())
return result;
map<string,vector<string>> m;
for(int i=0;i<strs.size();i++){
string temp=strs[i];
sort(temp.begin(),temp.end());
m[temp].push_back(strs[i]);
}
for(map<string,vector<string>>::iterator iter=m.begin();iter!=m.end();iter++)
result.push_back(iter->second);
return result;
}
};
笔记:
- 理解熟悉map的first,second的用法
- string也是一种容器,可以按照字母表顺序sort