【LeetCode】49. Group Anagrams
题目:
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.
提示:
此题的关键就是如何将所有anagrams word归类起来。举例来说,比如"ate", "eat","tea"三个单词,若按照字母顺序排序后,都将变为"aet"。因此我们可以对每个单词的字母进行排序,然后利用哈希表对他们进行归类。
代码:
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> result; int size = strs.size(); if (size == 0) return result; unordered_map<string, int> unmap; string tmp; for (int i = 0; i < size; ++i) { tmp = strs[i]; // 对每个单词,按照字母顺序排序 sort(tmp.begin(), tmp.end()); // 如果哈希表中没有出现过,则在哈希表中记录下这一类型单词插入到vector中的索引号 if (unmap.find(tmp) == unmap.end()) { unmap[tmp] = result.size(); result.push_back(vector<string>(1, strs[i])); } else { result[unmap[tmp]].push_back(strs[i]); } } // 一次对每一个子vector中的单词进行排序。 for (int i = 0; i < result.size(); ++i) { sort(result[i].begin(), result[i].end()); } return result; } };