Leetcode: Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
分析:此题的题意不是很明确,意思重新表述应该是一组string里面,有几个是anagram,找出这几个string。因为anagram具有相同个数的字符只是顺序有所改变,我们可以将string中字符排序后,再用一个unordered_map将anagram的几个string放到一起。代码如下:
class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> result; unordered_map<string, vector<string> > group; for(auto i:strs){ string tmp = i; sort(tmp.begin(), tmp.end()); group[tmp].push_back(i); } for(auto i = group.begin(); i != group.end(); i++){ if(i->second.size() > 1) result.insert(result.end(), i->second.begin(), i->second.end()); } return result; } };