码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Group Anagrams(同字符字符群)

时间:2015-11-06 19:28:39      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!