字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
代码如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hashmap;
for(auto s : strs){//遍历strs中的每一个字符串
string temp = s;
sort(temp.begin(), temp.end());//字母相同的字符串排完序之后结果相同
hashmap[temp].push_back(s);
}
int len = hashmap.size();
vector<vector<string>> ans(len);//存放结果
int index = 0;
for(auto i : hashmap){
ans[index] = i.second;
++ index;
}
return ans;
}
};
解释如下:
对于原字符串数组中的每一个字符串,通过sort对其排序,具有相同元素的字符串排序结果必然相同,再将排序过后的字符串作为hash的key,每一个排完序相同的字符串进入同一个字符串数组,也就是相同key值对应的字符串数组,这就是这个算法的核心思想。