給定一個字符串?dāng)?shù)組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。
示例:
輸入: ["eat", "tea", "tan", "ate", "nat", "bat"],
輸出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
說明:
所有輸入均為小寫字母。
不考慮答案輸出的順序。
關(guān)鍵:字典,key為排序后的字母序,value為return_list的下標
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = {}
i = 0
res = []
for _str in strs:
temp = "".join(sorted(_str))
if temp in d:
res[d[temp]].append(_str)
else:
d[temp] = i
res.append([_str])
i += 1
return res
關(guān)鍵:字典
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = {}
for x in strs:
key = tuple(sorted(x))
d[key] = d.get(key,[]) + [x]
return list(d.values())