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

Group Anagrams

时间:2015-10-01 06:56:21      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

 1 class Solution {
 2 public:
 3     vector<vector<string> > groupAnagrams(vector<string>& strs) {
 4         vector<vector<string> > result;
 5         if(strs.empty()) return result;
 6         
 7         sort(strs.begin(), strs.end());
 8         unordered_map<string, vector<int> > ht;
 9         
10         //initialize the hash table
11         //sort each string and map the same into hash table
12         for(int i = 0; i < strs.size(); i++){
13             string temp = strs[i];
14             sort(temp.begin(), temp.end());
15             ht[temp].push_back(i);
16         }
17         
18         for(unordered_map<string, vector<int> >::iterator ite = ht.begin(); ite != ht.end(); ite++){
19             vector<string> temp;
20             int n = (ite->second).size();
21             for(int i = 0; i < n; i++){
22                 temp.push_back(strs[(ite->second)[i]]);
23             }
24             result.push_back(temp);
25         }
26         return result;
27     }
28 };

 

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

 

Note:

  1. For the return value, each inner list‘s elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

Update (2015-08-09):
The signature of the function had been updated to return list<list<string>> instead of list<string>, as suggested here. If you still see your function signature return a list<string>, please click the reload button  to reset your code definition.

 

Group Anagrams

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4850595.html

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