2018-10-22 leetcode Group Anagrams Group Anagramsdict solution - 172ms 1234567891011class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ ret = {} for s in sorted(strs): key = tuple(sorted(s)) ret[key] = ret.get(key, []) + [s] return ret.values() defaultdict solution - 128ms 1234567import collectionsclass Solution(object): def groupAnagrams(self, strs): groups = collections.defaultdict(list) for s in strs: groups[tuple(sorted(s))].append(s) return map(sorted, groups.values()) itertools solution - 156ms 1234import itertoolsclass Solution(object): def groupAnagrams(self, strs): return [sorted(g) for _, g in itertools.groupby(sorted(strs, key=sorted), sorted)] test code 1234In [460]: s = Solution(); t = s.groupAnagrams(["eat","tea","tan","ate","nat","bat"])In [461]: tOut[461]: [['bat'], ['ate', 'eat', 'tea'], ['nat', 'tan']] leet code Python中collections.defaultdict()使用 理解 Python 语言中的 defaultdict Newer Maximum Subarray Older Kth Largest Element in an Array