题目描述:给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
这道题让我知道了,原来在 Python 中 tuple 是 hashable 的,也就是说可以拿一个 tuple 作为字典的 key,但是 list 是不可以的
def groupAnagrams(strs):
dic = {}
for word in strs:
count = [0] * 26
for l in word:
pos = ord(l) - ord('a')
count[pos] += 1
count = tuple(count)
if dic.get(count):
dic[count].append(word)
else:
dic[count] = [word]
return list(dic.values())