obsidian/笔记文件/2.笔记/字母异位词分组.md
2025-03-26 00:02:56 +08:00

1.4 KiB

!Pasted image 20220414231553.png

!Pasted image 20220414231556.png

!Pasted image 20220414231600.png

!Pasted image 20220414231606.png

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;

 }

};

!Pasted image 20220414231754.png

!Pasted image 20220414231804.png

class Solution {

public:

 vector<vector<string>> groupAnagrams(vector<string>& strs) {

 // 自定义对 array<int, 26> 类型的哈希函数

 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;

 }

};

!Pasted image 20220414231836.png