Group Anagrams -- LeetCode
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.
思路:使用哈希表。将所有字符串按照其内部字母排序后的结果进行分组。时间复杂度O(NlogN + Nmlogm)。其中N是单词数,m为最长的单词的长度。
补充:将一个字符串字母重新排序的算法:默认用sort函数是O(nlogn),其中n为字符串的长度。这里有一种O(n)的方法。方法是依次计数每一个字符在单词中出现的次数,然后按照字母序将出现过的单词重新拼出一个单词来。这种方法要求单词内的字母范围不能太大,而且会消耗额外空间。
1 class Solution { 2 public: 3 vector<vector<string>> groupAnagrams(vector<string>& strs) { 4 vector<vector<string> > res; 5 if (strs.size() == 0) return res; 6 unordered_map<string, vector<string> > dict; 7 for (int i = 0, n = strs.size(); i < n; i++) 8 { 9 string tem = strs[i]; 10 sort(tem.begin(), tem.end()); 11 if (dict.count(tem) == 0) 12 { 13 vector<string> cand(1, strs[i]); 14 dict.insert(make_pair(tem, cand)); 15 } 16 else dict[tem].push_back(strs[i]); 17 } 18 for (auto i : dict) 19 { 20 sort(i.second.begin(), i.second.end()); 21 res.push_back(i.second); 22 } 23 return res; 24 } 25 };