这题用到了默认字典,collections.defaultdict(list),键为元组,值为list.
最后的ans形式为:
defaultdict(list, {('a', 'e', 't'): ['eat', 'tea', 'ate'], ('a', 'n', 't'): ['tan', 'nat'], ('a', 'b', 't'): ['bat']})
最后输出value的部分,即ans.values
执行用时 :124 ms, 在所有 Python 提交中击败了44.33%的用户
内存消耗 :16.2 MB, 在所有 Python 提交中击败了19.03%的用户
Code:
class Solution(object):
def groupAnagrams(self, strs):
ans=collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()