leetcode 49. 字母异位词分组
使用sort+map的方法:
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string> > res; vector<string>cpy=strs; map<string,int> mp;int k=0; for(int i=0;i<strs.size();i++){ sort(strs[i].begin(),strs[i].end()); if(!mp.count(strs[i])){ mp[strs[i]]=k++;//cout<<mp[strs[i]]<<endl; } } for(int i=0;i<strs.size();i++){ if(res.size()<k) res.push_back({}); res[mp[strs[i]]].push_back(cpy[i]); } return res; } };
哈希表方法:将每个单词映射到0~26个字母,并且对每个字母的数目做出表示;
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string> > res; unordered_map<string,string> mp;int k=0; unordered_map<string,int> mp2; for(int i=0;i<strs.size();i++){ string ex="00000000000000000000000000"; for(int j=0;j<strs[i].size();j++){ ex[strs[i][j]-'a']+=1; } //cout<<ex<<endl; mp[strs[i]]=ex; if(!mp2.count(ex)) mp2[ex]=k++; } for(int i=0;i<strs.size();i++){ if(res.size()<k) res.push_back({}); res[mp2[mp[strs[i]]]].push_back(strs[i]); } return res; } };