给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
C++
class Solution {
public:
vector> groupAnagrams(vector& strs)
{
vector> res;
if(strs.empty())
{
return res;
}
int n=strs.size();
unordered_map> tmp;
for(int i=0;i>::iterator it;
//for(it=tmp.begin();it!=tmp.end();it++)
for(auto it:tmp)
{
res.push_back(it.second);
}
return res;
}
};
python
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
res=[]
if []==strs:
return res
n=len(strs)
dic={}
for i in range(n):
tmp=list(strs[i])
tmp.sort()
ss="".join(tmp)
if ss not in dic:
dic[ss]=[strs[i]]
else:
dic[ss].append(strs[i])
for key in dic:
res.append(dic[key])
return res