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

49. Group Anagrams

时间:2018-09-07 14:08:06      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:cond   example   you   red   pre   desc   题目   turn   字符   


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

标签:cond   example   you   red   pre   desc   题目   turn   字符   

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

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