struct mystat { int idx; int cnt[26]; mystat(int id = 0) {idx = id;} }; bool cmp(const mystat &a, const mystat &b) { for (int i=0; i<26; i++) { if (a.cnt[i] < b.cnt[i]) { return true; } else if (a.cnt[i] > b.cnt[i]) { break; } else { continue; } } return false; } bool same(const mystat &a, const mystat &b) { for (int i=0; i<26; i++) { if (a.cnt[i] != b.cnt[i]) return false; } return true; } class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> res; vector<mystat> stats; int len = strs.size(); for (int i=0; i<len; i++) { stats.push_back(mystat(i)); for (int j=strs[i].size() - 1; j>=0; j--) { stats.back().cnt[strs[i][j] - 'a']++; } } sort(stats.begin(), stats.end(), cmp); int si = 0; while (si < len ) { int i = si + 1; for (; i<len; i++) { if (same(stats[si], stats[i])) { res.push_back(strs[stats[i].idx]); } else { break; } } if (si + 1 < i) { res.push_back(strs[stats[si].idx]); } si = i; } return res; } };
虽然做出来了,不过写那么长,时间又是150ms+肯定还有什么巧妙的方法。
简短的版本:
class Solution { public: vector<string> anagrams(vector<string>& strs) { unordered_map<string, int> count; vector<string> res; int len = strs.size(); for (int i=0; i<len; i++) { string str = strs[i]; sort(str.begin(), str.end()); if (count.count(str) == 0) { count[str] = i; } else { if (count[str] >= 0) { res.push_back(strs[count[str]]); count[str] = -1; } res.push_back(strs[i]); } } return res; } };