将由同样的字符,不同排列组成的字符串聚在一起
解题思路:hashmap
- 将每一个字符相同的string,当做hashmap的key(字符相同,那就要对string进行排序喽)
- hashmap的second value 存的是index, 哪些值都对应这个key。(因此这存的是一组值要用vector)
- 最后遍历这个hashmap找每个key对应的index对应的string
vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<string> s(strs); vector<vector<string>> result; unordered_map<string, vector<int>> m; for(int i=0;i<s.size();i++) { sort(s[i].begin(),s[i].end()); m[s[i]].push_back(i); //m[s[i]]=i; } unordered_map<string,vector<int>>::iterator iter; for(iter=m.begin();iter!=m.end();iter++) { vector<string> temp; for(int i=0;i<iter->second.size();i++) { temp.push_back(strs[iter->second[i]]); } sort(temp.begin(),temp.end()); result.push_back(temp); } return result; }
或者更简单的方法,second value 存的不是index,存的是对应的string
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; unordered_map<string, vector<string>> mp; for(string s : strs){ string t = s; sort(t.begin(), t.end()); mp[t].push_back(s); } for(auto m : mp){ res.push_back(m.second); } return res; } };
可以不用find,自己定义算string 的key value。
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<int,vector<string>> d; vector<vector<string>> out; int index = 0; vector<int> num = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101}; for(auto x:strs){ index = 1; for(auto y:x){ index *= num[y-'a']; } d[index].push_back(x); } for(unordered_map<int,vector<string>>::iterator it = d.begin();it!=d.end();it++){ out.push_back(it->second); } return out; } };