题目
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
知识点
非暴力有两种方法【暴力方法,当strs中单词多了肯定不行。因为暴力的时间复杂度是 O(N^2)】。这里用到了collections这个包.
collections是个容器,里面有个defaultdict()对象,这个可以初始化一个字典。与普通字典不同,对于还未初始化的键,该字典可以按照 defaultdict() 所传入的类型 对该键设置初始值。
eg:普通的字典这么写,会因为没有对”key“ 初始化而报错
# 普通 dictionary:
dic_norm = {}
dic_norm["key"] = 1
但是对 collections.defaultdict 这么写ok
# collections default dictionary
import collections
dict_collections = collections.defaultdict(int) # 这里设置成int还是list等其他数据类型,看需要
dict_collections["key"] = 2
# 设置初始值
dict_collections = collections.defaultdict(lambda: 0)
dict_collections = collections.defaultdict(lambda: [1])
答案
方法一:
import collections
class Solution:
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for word in strs:
count = [0]*26
for c in word:
count[ord(c) - ord('a')] +=1 # ord 函数返回字符的asic码
ans[tuple(count)].append(word)
return ans.values() # collections.defaultdict和普通的dict一样,.values()函数范围value组成的list
方法二:
import collections
class Solution:
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for word in strs:
ans[tuple(sorted(word))].append(word)
return ans.values()
一开始用暴力写的,结果time out了,还是看的解答,涨知识了