给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
Method:
首先,将所有字符串排序,而异位词经过排序后拥有相同的顺序。
其次,将排序前后的字符分别作为Key和Value存入哈希表。
最后,遍历哈希表,将所有的Value保存到结果数组中。
Code:
class Solution {
public:
// 字母异位词分组
vector<vector<string>> groupAnagrams(vector<string> &strs) {
// 建立哈希表
// 使用排序后的字符作为Key
// 将原字符作为Value
unordered_map<string, vector<string>> result_map;
// 遍历所有的字符串
for(string &sub_str : strs)
{
// 暂时保存原来的字符串
string temp = sub_str;
// 字符串排序,排序之后得道Key
sort(temp.begin(), temp.end());
// 只要排序后一样,就将原来的字符加入当前键对应的值
result_map[temp].push_back(sub_str);
}
// 保存最终的结果
vector<vector<string>> result;
// 遍历哈希表
for(auto iter=result_map.begin();iter!=result_map.end();iter++)
{
// 记录键值对中的Value(Second)结果
result.push_back(iter->second);
}
// 返回结果
return result;
}
};
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/group-anagrams
Reference: