给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
主要是dict.get()函数的理解
dict.get(key, default=None)
- key – 字典中要查找的键。
- default – 如果指定键的值不存在时,返回该默认值。
还有一点要注意:因为字典的键,必须是不可变类型,所以用tuple。
代码实现:
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {}
for item in strs:
key = tuple(sorted(item))
#print('key:',key)
dict[key] = dict.get(key, []) + [item]
#print('dict:',dict)
return list(dict.values())
以示例一为例,print过程输出:
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’]}
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’]}
key: (‘a’, ‘n’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’], (‘a’, ‘n’, ‘t’): [‘tan’]}
key: (‘a’, ‘e’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’]}
key: (‘a’, ‘n’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’, ‘nat’]}
key: (‘a’, ‘b’, ‘t’)
dict: {(‘a’, ‘e’, ‘t’): [‘eat’, ‘tea’, ‘ate’], (‘a’, ‘n’, ‘t’): [‘tan’, ‘nat’], (‘a’, ‘b’, ‘t’): [‘bat’]}