首页 > 其他 > 详细

49. Group Anagrams

时间:2018-09-07 12:53:20      阅读:159      评论:0      收藏:0      [点我收藏+]

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.

题目要求把anagrams放在一起,可以考虑用hash table。对于hash table来讲,需要考虑key是什么:anagram排序后的字符串可以当作key
sort a string: 
sort(s.begin(),s.end());

  

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         unordered_map<string,vector<string>> map; //key:sorted string, value: vector of strings with the same key
 5         for(auto s: strs){
 6             string tmp = s;
 7             sort(tmp.begin(),tmp.end());
 8             map[tmp].push_back(s);
 9         }
10         
11         vector<vector<string>> result;
12         for(auto it: map){
13             result.push_back(it.second);
14         }
15         
16         return result;
17     }
18 };

 

49. Group Anagrams

原文:https://www.cnblogs.com/ruisha/p/9603865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!