leetcode 49 字母异位词分组
聪明的我又发现可以用上排序的方法,异位词在完成排序之后是一致的,所以可以遍历每一个词,对每个词进行排序,之后就得到每种异位词的特征,放进map里面,则解决问题,贴代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs)
{
int n = strs.size();
vector<vector<string>> res;
map <string,vector<string>> good;
for(int i = 0 ; i < n ; i ++ )
{
string temp = strs[i];
sort(strs[i].begin(),strs[i].end());
if(good.find(strs[i]) == good.end())
{
vector<string> temp_1 = {temp};
good.insert(pair<string,vector<string>>(strs[i],temp_1));
}
else
{
map<string,vector<string>>::iterator iter= good.find(strs[i]);
iter->second.push_back(temp);
}
}
map<string,vector<string>>::iterator temp = good.begin();
while(temp!= good.end())
{
res.push_back(temp->second);
temp++;
}
return res;
}
};

浙公网安备 33010602011771号