题目描述:
Given an array of strings, group anagrams together.
For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
思路:
首先对所给的字符串列表(数组)进行排序,即对其中的每一个字符串都进行排序,这样就可以得到哪些字符串是归位一组的。
接着将字符串列表转换为一个字典,并遍历key值得到最终的列表返回。
AC代码:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ans, res, ret = [], {}, []
for s in strs:
temp = list(s)
temp.sort()
ans.append("".join(temp))
for i in range(len(ans)):
if ans[i] not in res:
res[ans[i]] = []
res[ans[i]].append(strs[i])
for key in res:
ret.append(res[key])
return ret
584


&spm=1001.2101.3001.11974&articleId=76732799&d=1&t=3&u=3f30f83bf08749b5befa6666d66c880b)

被折叠的 条评论
为什么被折叠?



