# 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入:[eat", "tea", "tan", "ate", "nat", "bat"]
输出:[[ate","eat","tea"],["nat","tan"],["bat"]]
说明:
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector> res;
res = sol.groupAnagrams(strs);
for (auto i : res)
{
for (auto j : i)
cout << j << " ";
cout << endl;
}
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
vector> groupAnagrams(vector &strs)
{
vector> res;
map kvmap;
string s;
int index = 0;
for (int i = 0; i < strs.size(); i++)
{
s = strs[i];
sort(s.begin(), s.end());
if (kvmap.find(s) == kvmap.end())
{
index++;
res.push_back(vector{});
}
res[kvmap[s]].push_back(strs[i]);
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector> groupAnagrams(vector &strs)
{
vector> res;
unordered_map> ht;
for (const auto &str : strs)
{
int counts[26] = {0};
for (char c : str)
{
counts[c - 'a']++;
}
string key;
for (int i : counts)
{
key.push_back('#');
key.push_back(i + '0');
}
ht[key].push_back(str);
}
for (const auto &t : ht)
{
res.push_back(t.second);
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector> groupAnagrams(vector &strs)
{
map> anagram;
vector> result;
for (int i = 0; i < strs.size(); i++)
{
string str = strs[i];
sort(str.begin(), str.end());
if (anagram.find(str) == anagram.end())
{
std::vector item;
anagram[str] = item;
}
anagram[str].push_back(strs[i]);
}
map>::iterator it;
for (it = anagram.begin(); it != anagram.end(); it++)
{
result.push_back((*it).second);
}
return result;
}
};
```
### C
```cpp
class Solution
{
public:
vector> groupAnagrams(vector &strs)
{
int len = strs.size();
if (len == 0)
return {{""}};
std::map mymap;
vector> ans;
int cur = 0;
for (int i = 0; i < len; i++)
{
string tmp(strs[i]);
sort(tmp.begin(), tmp.end());
std::map::iterator it = mymap.find(tmp);
if (it != mymap.end())
{
ans[it->second].push_back(strs[i]);
}
else
{
vector item;
item.push_back(strs[i]);
ans.push_back(item);
mymap.insert(make_pair(tmp, cur));
cur++;
}
}
return ans;
}
};
```