https://leetcode.cn/problems/group-anagrams/
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {unordered_map<string,vector<string>>map;//哈希表鍵為排序后或者處理后的字符串,值為某一種字母異位詞對應的字符串for(string str:strs){//構造字符串對應的鍵值,字母加字母出現次數int count[26]={0};for(char a:str){count[a-'a']++;}string key;for(int i=0;i<26;i++){if(count[i]!=0){key.push_back(i+'a');key.push_back(count[i]+'0');}}map[key].push_back(str);}vector<vector<string>>res;//for(auto p=map.begin;p!=map.end();p++)for(auto& p:map)//unordered_map的迭代器是一個指針,指向這個元素,通過迭代器來取得它的值。{res.emplace_back(p.second);//emplace_back構造及插入一個元素//res.push_back(p.second);}return res;}
};
直接排序:
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {unordered_map<string,vector<string>>map;//哈希表鍵為排序后或者處理后的字符串,值為某一種字母異位詞對應的字符串for(string str:strs){string key=str;sort(key.begin(),key.end());map[key].push_back(str);}vector<vector<string>>res;//for(auto p=map.begin;p!=map.end();p++)for(auto& p:map)//unordered_map的迭代器是一個指針,指向這個元素,通過迭代器來取得它的值。{res.emplace_back(p.second);//emplace_back構造及插入一個元素//res.push_back(p.second);}return res;}
};