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:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
思路:使用哈希表,将每个单词按照其内部字母排序后的结果进行映射。anagram会被映射到同一组中。
1 class Solution { 2 public: 3 vector<vector<string>> groupAnagrams(vector<string>& strs) { 4 sort(strs.begin(), strs.end()); 5 unordered_map<string, vector<string> > dict; 6 for (int i = 0, n = strs.size(); i < n; i++) 7 { 8 string b = strs[i]; 9 sort(b.begin(), b.end()); 10 if (dict.count(b)) dict[b].push_back(strs[i]); 11 else 12 { 13 vector<string> tem(1, strs[i]); 14 dict.insert(make_pair(b, tem)); 15 } 16 } 17 vector<vector<string> > res; 18 for (auto i : dict) 19 res.push_back(i.second); 20 return res; 21 } 22 };