题解 | #牛棚品种分类#
牛棚品种分类
https://www.nowcoder.com/practice/0b6068f804b9426aa737ea8606e8d5c3
考察的知识点:字符串;
解答方法分析:
- 创建一个无序哈希表 hashMap,用于存储排序后的字符串作为键和对应的原始字符串作为值。这里使用 unordered_map 容器。
- 遍历输入的字符串数组 strs,对每个字符串进行如下处理:将当前字符串 x 复制给新的变量 s。对 s 进行排序操作,将其变成有序字符串。判断有序字符串 s 是否存在于哈希表 hashMap 中,若不存在,则将 s 作为键,x 作为值加入哈希表;若存在,则将 x 添加到对应值的末尾,并以逗号分隔。
- 创建一个字符串数组 result,用于存储最终的分组结果。
- 遍历哈希表 hashMap 的键值对,将每个值(即原始字符串)依次添加到 result 数组中。
- 对 result 数组进行排序,使得结果按字典序排列。
- 返回排序后的 result 数组作为函数的输出结果。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param strs string字符串vector * @return string字符串vector */ vector<string> groupAnagrams(vector<string>& strs) { unordered_map<string, string> hashMap; for (auto x : strs) { string s = x; sort(s.begin(), s.end()); if (hashMap.find(s) == hashMap.end()) { hashMap[s] = x; } else { hashMap[s] += "," + x; } } vector<string> result; for (auto x : hashMap) { result.push_back(x.second); } sort(result.begin(), result.end()); return result; } };