https://leetcode.com/problems/anagrams/
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:
class node { public: int idx; string s; node(int i, string str) { idx =i; s = str; } bool operator < (const node& rhs) { if(s.compare(rhs.s) < 0 || (s.compare(rhs.s) == 0 && idx < rhs.idx)) return true; return false; } }; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string> > res; int n = strs.size(); if(n == 0) return res; if(n == 1) { vector<string> tmp; tmp.push_back(strs[0]); res.push_back(tmp); return res; } vector<vector<char> > vec(n); vector<node> cs; for(int i=0; i<n; ++i) { for(int j=0; j<strs[i].length(); ++j) { vec[i].push_back(strs[i][j]); } sort(vec[i].begin(), vec[i].end()); string ss = ""; for(int k=0; k<vec[i].size(); ++k) { ss += vec[i][k]; } cs.push_back(node(i, ss)); } sort(cs.begin(), cs.end()); int l = 0, r = l+1; while(r < n) { while(r < n && (cs[l].s).compare(cs[r].s) == 0) ++r; vector<string> row; for(int p=l; p<r; ++p) row.push_back(strs[cs[p].idx]); res.push_back(row); l = r; r = l+1; } if(l < n) { vector<string> row; row.push_back(strs[cs[n-1].idx]); res.push_back(row); } for(int i=0; i<res.size(); ++i) { sort(res[i].begin(), res[i].end()); } return res; } };
leetcode@ [49] Group Anagrams (Hashtable)
原文:http://www.cnblogs.com/fu11211129/p/5202574.html