49. 字母异位词分组
题意:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
解题思路:
这道题我是看了官方解答才知道用排序和哈希表做的,自己没想出来,一直在想着怎么跟首个去比较.时间复杂度太高过不了,看了之后才想到用排序后同一个词就是同一个样子,然后自己做了一下. 基本就是
- 遍历每一个字符
- 字符排序
- 压入哈希表
- 遍历整个哈希表,获取结果
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> map;
for (auto &str : strs)
{
string k = str;
sort(k.begin(), k.end());
map[k].push_back(str);
}
vector<vector<string>> res;
for (auto it = map.begin(); it != map.end(); it++)
{
res.push_back(it->second);
}
return res;
}
};
运行结果:
总结:
自己一直在试逐个比较,运行发现时间太长.看了官方解法才知道用排序和哈希表结合.排序这一步没能想到.