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: All inputs will be in lower-case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public : vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> map; for (auto s: strs){ string key = s; sort(key.begin(), key.end()); map[key].push_back(s); } vector<vector<string>> anagrams; for (auto m:map){ anagrams.push_back(m.second); } return anagrams; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public : vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, multiset<string>> map; for (auto s: strs){ string key = s; sort(key.begin(), key.end()); map[key].insert(s); } vector<vector<string>> anagrams; for (auto m:map){ vector<string> anagram(m.second.begin(), m.second.end()); anagrams.push_back(anagram); } return anagrams; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public : int prime[26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103}; vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map< long , vector<string>> map; for (auto s: strs){ map[hash_value(s)].push_back(s); } vector<vector<string>> result; for (auto m: map){ result.push_back(m.second); } return result; } long hash_value(string s){ long value = 1; for (auto c: s){ value *=prime[c- ‘a‘ ]; } return value; } }; |
原文:http://www.cnblogs.com/zhxshseu/p/f87c737b95b7e58c7ca48936fee74b9e.html