Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
思路:
用map和set,set用来保存属于同一个anagram的string,map,用来对应不同的anagram。
vector<vector<string> > groupAnagrams(vector<string>& strs) { vector<vector<string> >group; if(strs.size()==0)return group; map<string,set<string> >m; for(int i=0;i<strs.size();i++) { string temp = strs[i]; sort(temp.begin(),temp.end()); m[temp].insert(strs[i]); } map<string,set<string> >::iterator it; for(it = m.begin();it!=m.end();it++) { vector<string> anagram; set<string>::iterator setit; for(setit = it->second.begin();setit!=it->second.end();setit++) { anagram.push_back(*setit); } group.push_back(anagram); } return group; }
如上,总是不能通过测试用例["",""],而且写的感觉也啰嗦,如下是参考的别人的:
vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, multiset<string>> mp; for (string s : strs) { string t = s; sort(t.begin(), t.end()); mp[t].insert(s); } vector<vector<string>> anagrams; for (auto m : mp) { vector<string> anagram(m.second.begin(), m.second.end()); anagrams.push_back(anagram); } return anagrams; }
参考:
https://discuss.leetcode.com/topic/21038/10-lines-76ms-easy-c-solution-updated-function-signature