Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
题意理解有些困惑,其实是返回变位词个数大于等于2的所有单词,全部放到一个vector里面去。
然后就比较简单了,编程珠玑里面有提到。
class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> result; if (strs.size() <= 1) { return result; } vector<pair<string, string>> strnodes; string sorted; for (int i = 0; i < strs.size(); ++i) { sorted = strs[i]; sort(sorted.begin(), sorted.end()); strnodes.push_back(make_pair(strs[i], sorted)); } sort(strnodes.begin(), strnodes.end(), anagram_less); int count = 1; sorted = strnodes[0].second; int i = 1; for (; i < strnodes.size(); ++i) { if (strnodes[i].second == sorted) { ++count; } else { if (count >= 2) { for (int j = i - count; j < i; ++j) { result.push_back(strnodes[j].first); } } sorted = strnodes[i].second; count = 1; } } if (count >= 2) { for (int j = i - count; j < i; ++j) { result.push_back(strnodes[j].first); } } return result; } static bool anagram_less(pair<string, string> p1, pair<string, string> p2) { return p1.second < p2.second; } };
================第二次=================
class Solution { public: vector<string> anagrams(vector<string> &strs) { unordered_map<string, multiset<string>> groups; for (int i = 0; i < strs.size(); ++i) { string sorted = strs[i]; sort(sorted.begin(), sorted.end()); auto iter = groups.find(sorted); if (iter == groups.end()) { multiset<string> group; group.insert(strs[i]); groups[sorted] = group; } else { iter->second.insert(strs[i]); } } vector<string> result; for (auto iter = groups.begin(); iter != groups.end(); ++iter) { if (iter->second.size() >= 2) { result.insert(result.end(), iter->second.begin(), iter->second.end()); } } return result; } };
class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> result; unordered_map<string, int> groups; for (int i = 0; i < strs.size(); ++i) { string sorted = strs[i]; sort(sorted.begin(), sorted.end()); auto iter = groups.find(sorted); if (iter == groups.end()) { groups.insert({sorted, i}); } else { result.push_back(strs[i]); if (iter->second >= 0) { result.push_back(strs[iter->second]); iter->second = -1; } } } return result; } };