leetcode 49. Group Anagrams 使用【python】求解
题目:
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.
提示:
题中需要把相同字母组成的单词归为一类,故可以用dict进行实现。将单词拆分排序后作为key,value为一个list,将排序前的单词插入list。
代码:
def groupAnagrams(strs): ans = {} for s in strs: tmp = tuple(sorted(s)) if tmp in ans: ans[tmp].append(s) else: ans[tmp] = [s] return list( ans.values() )
在Python中如果访问字典中不存在的键,会引发KeyError异常。因此,可以采用collections.defaultdict来初始化字典。defaudict初始化函数接受一个类型作为参数,当访问不存在的key时,可以实例化一个值作为默认值,从而省去了使用dict时需要判断key是否存在的问题。代码如下:
import collections
def groupAnagrams(strs): ans = collections.defaultdict(list) for s in strs: ans[tuple(sorted(s))].append(s) return list( ans.values() )
函数中sorted的时间复杂度为O(nlgn),因此可以考虑使用计数排序进行优化。代码如下:
import collections
def groupAnagrams(strs): ans = collections.defaultdict(list) for s in strs: count = [0] * 26 for c in s: count[ord(c) - ord('a')] += 1 ans[tuple(count)].append(s) return list( ans.values() )
浙公网安备 33010602011771号