标签:
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实现,将每个字符排下序作为key就可以了,代码如下:
1 class Solution { 2 public: 3 vector<vector<string>> groupAnagrams(vector<string>& strs) { 4 vector<vector<string>> ret; 5 map<string, vector<string>> res; 6 string tmp; 7 for(int i = 0; i < strs.size(); ++i){ 8 tmp = strs[i]; //这里是关键 9 sort(tmp.begin(), tmp.end()); 10 res[tmp].push_back(strs[i]); 11 } 12 vector<string> tmpVec; 13 for(typename map<string, vector<string>>::iterator it = res.begin(); it != res.end(); ++it){ 14 sort(it->second.begin(), it->second.end()); 15 } 16 for(typename map<string, vector<string>>::iterator it = res.begin(); it != res.end(); ++it){ 17 tmpVec.clear(); 18 if(it->second.size() >= 1) 19 for(int i = 0; i < it->second.size(); i++){ 20 tmpVec.push_back(it->second[i]); 21 } 22 ret.push_back(tmpVec); 23 } 24 return ret; 25 } 26 };
还有很多种实现方法实际上,以后再来一一实现
LeetCode OJ:Group Anagrams(同字符字符群)
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4943301.html