Group Anagrams
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.
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > res;
if(strs.size() == 0) return res;
int id = -1;
unordered_map<string, int> m;
for(int i = 0; i < strs.size(); ++i){
string str = strs[i];
sort(str.begin(), str.end());
if(m.find(str) == m.end()){
m[str] = ++id;
res.push_back(vector<string>());
} res[m[str]].push_back(strs[i]);
} return res;
}
};