题目连接
Group Anagrams
Description
Given an array of strings, group anagrams together.
For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:[
[“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.以一种奇怪的方式水过去了... __(:з」∠)__
class Solution {public: vector> groupAnagrams(vector & strs) { if (!strs.size()) return ans; int n = strs.size(); vector *ret = new vector [n]; for (int i = 0; i < n; i++) { string x = strs[i]; sort(x.begin(), x.end()); if (vis.find(x) == vis.end()) { vis[x] = i, index.insert(i); ret[i].push_back(strs[i]); } else { int v = vis[x]; vis[strs[i]] = v; ret[v].push_back(strs[i]); } } for (set ::iterator i = index.begin(); i != index.end(); ++i) { sort(ret[*i].begin(), ret[*i].end()); ans.push_back(ret[*i]); } sort(ans.begin(), ans.end(), cmp()); delete []ret; return ans; }private: struct cmp { bool operator()(const vector &A, const vector &B) { int m = (int)A.size(), n = (int)B.size(); return n == m ? A[0] > B[0] : (bool)(n > m); } }; set index; unordered_map vis; vector > ans;};