49. Group Anagrams
题目大意
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
中文释义
给定一个字符串数组 strs
,将变位词组合在一起。答案可以以任何顺序返回。
变位词是指通过重新排列不同单词或短语的字母而形成的单词或短语,通常使用所有原始字母恰好一次。
示例
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
限制条件
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i]
由小写英文字母组成。
解题思路
方法
这个解决方案用于解决“Group Anagrams”问题,即将具有相同字母但排列不同的字符串分组。主要方法是使用哈希表来分组具有相同字符集的字符串。
-
创建哈希表:
- 使用
unordered_map<string, vector<string>>
。键是排序后的字符串,值是原始字符串的数组。
- 使用
-
遍历并分组:
- 遍历字符串数组
strs
。对于每个字符串s
:- 创建一个临时字符串
t
,并将s
的内容复制到t
。 - 对临时字符串
t
进行排序,使其字符按字典顺序排列。 - 将原始字符串
s
添加到哈希表的相应键(即排序后的字符串t
)下的数组中。
- 创建一个临时字符串
- 遍历字符串数组
-
提取结果:
- 遍历哈希表,将哈希表中的每个值(即每个分组的字符串数组)添加到最终结果
anagrams
中。
- 遍历哈希表,将哈希表中的每个值(即每个分组的字符串数组)添加到最终结果
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> map;
for (string& s : strs) {
string t = s;
sort(t.begin(), t.end()); // 对字符串进行排序
map[t].push_back(s); // 添加到映射中
}
vector<vector<string>> anagrams;
for (auto& pair : map) {
anagrams.push_back(pair.second); // 将哈希表中的值添加到结果中
}
return anagrams;
}
};