数组同构分组

题目

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],

ouput:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]

思路

运用hashmap来解决

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int n=strs.size();
if(n==0) return vector<vector<string>> ();

vector<vector<string>> res;
unordered_map<string, vector<string>> hash;
//(1)将字符串数组先按字典顺序排序
sort(strs.begin(), strs.end());
//(2)构造hash表
for(int i=0;i<n;i++)
{//将排序后相等的字符串放在相同的vector
string tmp=strs[i];
sort(tmp.begin(), tmp.end());
hash[tmp].push_back(strs[i]);
}
unordered_map<string, vector<string>>::iterator it;
for(it=hash.begin();it != hash.end();it++)
{//(3)将hash表中的value值(数组形式)放到结果数组
res.push_back(it->second);
}
return res;
}
};