题目
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
思路
考虑使用一个哈希表,键为每个字符串经过sort之后的字符串(保证唯一性),值为原来的字符串都存储在vector里面。
#include <vector>
#include <string>
#include <iostream>
#include <unordered_map>
using namespace std;
vector<vector<string> > solotion(vector<string> strs)
{
int n = strs.size();
unordered_map<string, vector<string>> hash_map;
vector<vector<string>> ans;
for(int i = 0; i<n; i++)
{
string temp = strs[i];
sort(temp.begin(), temp.end());
hash_map[temp].emplace_back(strs[i]);
}
for(auto it : hash_map)
{
ans.emplace_back(it.second); // 什么时候用-> : 对象在堆上(C++ new出来的指针用),其他时候用.
// 如果是指针访问数据成员,用->,如果是对象访问成员函数成员变量,用.
}
return ans;
}