LeetCode 49. Group Anagrams

unordered_map< string, vector<string> >map;存sort之后的每个string及其一串anagram。只是函数的简单调用。注释部分是另一种语法,思路是一样的。

 

 1 class Solution {
 2 public:
 3     string Sort(string a){
 4         int len = a.length();
 5         int cnt[27] = {0};
 6         for(int i = 0; i < a.length(); ++i){
 7             ++cnt[a[i] - 'a'];
 8         }
 9         string res = "";
10         for(int i = 0; i < 27; ++i){
11             int tmp = cnt[i];
12             while(tmp){
13                 res += char(i + 'a');
14                 --tmp;
15             }
16         }
17         return res;
18     }
19     vector<vector<string>> groupAnagrams(vector<string>& strs) {
20         unordered_map< string, vector<string> >map;
21         for(int i = 0; i <strs.size(); ++i){
22             string copy = strs[i];
23             sort(copy.begin(), copy.end());
24             // copy = Sort(copy);
25             if(map.find(copy) == map.end()){
26                 vector<string> anagrams;
27                 anagrams.push_back(strs[i]);
28                 map[copy] = anagrams;
29             }
30             else map[copy].push_back(strs[i]);
31         }
32         
33         vector< vector<string> >res;
34         for(auto str : map){
35             sort(str.second.begin(), str.second.end());
36             vector<string> tmp = str.second;
37             
38             res.push_back(tmp);
39         }
40         return res;
41         
42         // for(auto &p : classfication){
43         //     sort(classfication[p.first].begin(), classfication[p.first].end());
44         //     ans.push_back(classfication[p.first]);
45         // }
46     }
47 };

 

posted @ 2016-03-20 21:13  co0oder  阅读(209)  评论(0编辑  收藏  举报