LeetCode链接
排序作为dict的键 时间复杂度 O(n * klogk)
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = collections.defaultdict(list)
for str in strs:
dic[''.join(sorted(str))].append(str)
return list(dic.values())
计数 时间复杂度 O(n * (k + 26))
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = collections.defaultdict(list)
ordA = ord('a')
for str in strs:
l = [0] * 26
for c in str:
l[ord(c) - ordA] += 1
dic[tuple(l)].append(str)
return list(dic.values())