题目描述:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
方法1:
主要思路:
(1)生成原数组的副本,将副本中的每个数组进行排序,这样就将每个异位词统一成了相同的次;
(2)对排序后的副本进行unordered_map映射,在映射的过程中,能够映射到相同位置的字符串,在原始的数组中对应的索引处找出,压入到对应的res的字符串数组中,res中对应的位置是通过map获得的;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<string> tmp=strs;
//对原始数组的副本中每个元素进行排序
for(string& str:tmp){
sort(str.begin(),str.end());
}
vector<vector<string>> res;
unordered_map<string,int> mp;//映射使用的数组
//遍历排序后的数组,对相同的字符串映射到res中对应存储位置索引上
for(int i=0;i<tmp.size();++i){
if(mp.count(tmp[i])){
res[mp[tmp[i]]].push_back(strs[i]);//之前出现过的,将对应的原数组中元素压入到结果中
}
else{
mp[tmp[i]]=res.size();//将res中将要存储该类字符串的索引位置存储到map中
res.push_back(vector<string>(1,strs[i]));//将当前字符串压入到res的新的元素中
}
}
return res;
}
};