【C++算法】60.哈希表_字母异位词分组
文章目录
- 题目链接:
- 题目描述:
- 解法
- C++ 算法代码:
- 解释
- 第1步:处理 "eat"
- 第2步:处理 "tea"
- 第3步:处理 "tan"
- 第4步:处理 "ate"
- 第5步:处理 "nat"
- 第6步:处理 "bat"
- 提取结果
题目链接:
49. 字母异位词分组
题目描述:
解法
哈希表
- 判断两个字符串是不是字母异位词(排序)
- 分组
<string,string[]>
例如:
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
aet --> eat,tea,ate
ant --> tan,nat
abt --> bat
最后遍历哈希表,把里面的value提取出来。
C++ 算法代码:
class Solution
{
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {// 创建哈希表,键为排序后的字符串(作为字母异位词的标识)// 值为原始字符串的集合(即所有属于该异位词组的原始字符串)unordered_map<string, vector<string>> hash;// 1. 遍历所有字符串,将字母异位词分组for(auto& s : strs){// 创建字符串副本并排序string tmp = s;sort(tmp.begin(), tmp.end());// 排序后的字符串作为键,原始字符串添加到对应的异位词组中// 例如:"eat"、"tea"、"ate" 排序后都是 "aet",因此会被分到同一组hash[tmp].push_back(s);}// 2. 从哈希表中提取结果,构建返回值vector<vector<string>> ret;// 使用结构化绑定遍历哈希表中的每个键值对// x是排序后的字符串(键),y是对应的字母异位词组(值)for(auto& [x, y] : hash){// 将每个异位词组添加到结果中ret.push_back(y);}return ret;}
};
解释
例如:strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
第1步:处理 “eat”
- 创建副本并排序:
tmp = "eat" → sort → "aet"
- 检查哈希表:
hash["aet"]
不存在 - 插入到哈希表:
hash["aet"] = ["eat"]
- 哈希表现在:
hash = {"aet": ["eat"]}
第2步:处理 “tea”
- 创建副本并排序:
tmp = "tea" → sort → "aet"
- 检查哈希表:
hash["aet"]
已存在,其值为["eat"]
- 更新哈希表:
hash["aet"].push_back("tea")
添加原字符串 - 哈希表现在:
hash = {"aet": ["eat", "tea"]}
第3步:处理 “tan”
- 创建副本并排序:
tmp = "tan" → sort → "ant"
- 检查哈希表:
hash["ant"]
不存在 - 插入到哈希表:
hash["ant"] = ["tan"]
- 哈希表现在:
hash = {"aet": ["eat", "tea"], "ant": ["tan"]}
第4步:处理 “ate”
- 创建副本并排序:
tmp = "ate" → sort → "aet"
- 检查哈希表:
hash["aet"]
已存在,其值为["eat", "tea"]
- 更新哈希表:
hash["aet"].push_back("ate")
添加原字符串 - 哈希表现在:
hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan"]}
第5步:处理 “nat”
- 创建副本并排序:
tmp = "nat" → sort → "ant"
- 检查哈希表:
hash["ant"]
已存在,其值为["tan"]
- 更新哈希表:
hash["ant"].push_back("nat")
添加原字符串 - 哈希表现在:
hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"]}
第6步:处理 “bat”
- 创建副本并排序:
tmp = "bat" → sort → "abt"
- 检查哈希表:
hash["abt"]
不存在 - 插入到哈希表:
hash["abt"] = ["bat"]
- 哈希表现在:
hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"], "abt": ["bat"]}
提取结果
遍历哈希表中的每个键值对,提取值部分(字符串组):
- 键
"aet"
对应的值["eat", "tea", "ate"]
→ 添加到ret
- 键
"ant"
对应的值["tan", "nat"]
→ 添加到ret
- 键
"abt"
对应的值["bat"]
→ 添加到ret
最终结果:ret = [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]