49. 字母异位词分组

 

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

 

 

字符串排序,当key

 

 1 class Solution:
 2     def groupAnagrams(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: List[List[str]]
 6         """
 7         d = {}
 8         for s in strs:
 9             key = ''.join(sorted(s))
10             
11             if key in d:
12                 d[key].append(s)
13             else:
14                 d[key] = [s]
15         res = []
16         for key in d:
17             res.append(d[key])
18         return res

 

 

 

c++:

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         vector<vector<string>> res ;
 5         unordered_map<string,vector<string>> d ;
 6         for(string& s :strs){
 7             string key = s;
 8             sort(key.begin(),key.end());
 9             d[key].push_back(s);
10         }
11         for(auto &item :d)
12             res.push_back(item.second);
13         return res;
14     }
15 };

 

posted @ 2018-12-21 16:52  乐乐章  阅读(156)  评论(0编辑  收藏  举报