LeetCode49
两个方法:
1.给单词排序
按照a-z,比如eat,排完序过后就是aet,那么排完序后对应相同字符串的字符串归类到同一个集合里面
{
aet:[“ate”,“eat”,“tea”]
abt:[“bat”]
ant:[“nat”,“tan”]
}
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>> mp; for (string& str: strs) { string key = str; sort(key.begin(), key.end()); mp[key].emplace_back(str); } vector<vector<string>> ans; for (auto it = mp.begin(); it != mp.end(); ++it) { ans.emplace_back(it->second); } return ans; } };
|
2.哈希法
定义一个长26的数组shuzu,表示a-z是否出现,例如shuzu[0]=1,则表示a出现。
那么eat对应的数组是[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,…,1,…]
最后对应数组相同的归类为一组。
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 26
| class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { auto arrayHash = [fn = hash<int>{}] (const array<int, 26>& arr) -> size_t { return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) { return (acc << 1) ^ fn(num); }); };
unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp(0, arrayHash); for (string& str: strs) { array<int, 26> counts{}; int length = str.length(); for (int i = 0; i < length; ++i) { counts[str[i] - 'a'] ++; } mp[counts].emplace_back(str); } vector<vector<string>> ans; for (auto it = mp.begin(); it != mp.end(); ++it) { ans.emplace_back(it->second); } return ans; } };
|