leetcode 49. 字母异位词分组 medium
题目描述:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
解题思路:
遍历数组,将每个字符串都给排序一下,然后加到哈希表中去,也可以不排序(只要找到一种方法,能够使得拥有相同字符的字符串的哈希值一样,而不同字符的哈希值不一样,即可)
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//遍历数组,将每个字符串都给排序一下,然后加到哈希表中去
unordered_map<string, vector<string>> hash;
for(auto s:strs){
string key=s;
sort(key.begin(),key.end());
hash[key].push_back(s);
}
vector<vector<string>> res;
for(auto i:hash){
res.push_back(i.second);
}
return res;
}
};