leetcode@ [49] Group Anagrams (Hashtable)

时间:2023-03-09 01:00:26
leetcode@ [49] Group Anagrams (Hashtable)

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.
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) < || (s.compare(rhs.s) == && 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 == ) return res;
if(n == ) {
vector<string> tmp;
tmp.push_back(strs[]);
res.push_back(tmp);
return res;
} vector<vector<char> > vec(n);
vector<node> cs;
for(int i=; i<n; ++i) {
for(int j=; j<strs[i].length(); ++j) {
vec[i].push_back(strs[i][j]);
}
sort(vec[i].begin(), vec[i].end()); string ss = "";
for(int k=; k<vec[i].size(); ++k) {
ss += vec[i][k];
}
cs.push_back(node(i, ss));
}
sort(cs.begin(), cs.end()); int l = , r = l+;
while(r < n) {
while(r < n && (cs[l].s).compare(cs[r].s) == ) ++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+;
} if(l < n) {
vector<string> row;
row.push_back(strs[cs[n-].idx]);
res.push_back(row);
}
for(int i=; i<res.size(); ++i) {
sort(res[i].begin(), res[i].end());
} return res;
}
};