Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
1 class Solution { 2 public: 3 vector<vector<string> > groupAnagrams(vector<string>& strs) { 4 vector<vector<string> > result; 5 if(strs.empty()) return result; 6 7 sort(strs.begin(), strs.end()); 8 unordered_map<string, vector<int> > ht; 9 10 //initialize the hash table 11 //sort each string and map the same into hash table 12 for(int i = 0; i < strs.size(); i++){ 13 string temp = strs[i]; 14 sort(temp.begin(), temp.end()); 15 ht[temp].push_back(i); 16 } 17 18 for(unordered_map<string, vector<int> >::iterator ite = ht.begin(); ite != ht.end(); ite++){ 19 vector<string> temp; 20 int n = (ite->second).size(); 21 for(int i = 0; i < n; i++){ 22 temp.push_back(strs[(ite->second)[i]]); 23 } 24 result.push_back(temp); 25 } 26 return result; 27 } 28 };
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
Update (2015-08-09):
The signature of the function had been updated to return list<list<string>>
instead of list<string>
, as suggested here. If you still see your function signature return a list<string>
, please click the reload button to reset your code definition.