49. Group Anagrams
Posted ruisha
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了49. Group Anagrams相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章