字母异位词分组49
tags:
- 哈希表
- 字符串
- 排序
地址:https://leetcode.cn/problems/group-anagrams
题干
给你一个字符串数组,请你将字母异位词组合在一起。可以按任意顺序返回结果列表。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
解释:
在 strs 中没有字符串可以通过重新排列来形成 "bat"。 字符串 "nat" 和 "tan" 是字母异位词,因为它们可以重新排列以形成彼此。 字符串 "ate" ,"eat" 和 "tea" 是字母异位词,因为它们可以重新排列以形成彼此。
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
思路
题解
注意:本题用的pairs.second是对于对象/引用的方法,使用点操作符.来访问其成员。
不要和second指针混淆。xxx->second — 用于指针或迭代器。
若要改用迭代器:
for (auto it = umap.begin(); it != umap.end(); ++it) {
result.push_back(it->second); // it 是迭代器,用 ->second
}
以下是完整题解:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> umap;
for (const string& s : strs) {
string key = s;
sort(key.begin(), key.end());
umap[key].push_back(s);
}
vector<vector<string>> result;
for (auto& pairs : umap) {
result.push_back(pairs.second);
}
return result;
}
};