Description:
题目大意:给定一个字符串数组,返回字母相同的字符串数组。
解题思路::
算法标签:哈希表
1.将排序好的字符串设置为key
2. 然后存储对应的字符串
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 建立一个哈希表
unordered_map<string,vector<string>>hash_mp;
// 遍历字符串数组
for(auto str : strs) {
string key = str;
// 字母从小到大排序
sort(key.begin(),key.end());
// 排序后把对应的字符串放入哈希表中
hash_mp[key].push_back(str);
}
// 把hash表中的字符串返回给ans
vector<vector<string>>ans;
for(auto iter = hash_mp.begin();iter != hash_mp.end();iter++) {
ans.push_back(iter -> second);
}
return ans;
}
};