【LeetCode】49.字母异位词分组
文章目录
- 题目
- 1. 排序
- 2. 计数
题目
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
1. 排序
- 排序的str作为键
- 将原str添加为键值
- 最后返回键值作为list
class Solution(object):def groupAnagrams(self, strs):""":type strs: List[str]:rtype: List[List[str]]""""""1.排序的str作为键2.将原str添加为键值3.最后返回键值作为list"""mp = defaultdict(list)for str in strs:key = "".join(sorted(str))mp[key].append(str)return list(mp.values())
- 使用
sorted(s)
对每个字符串进行排序,''.join(sorted(s))
将该列表拼接成一个新的字符串,作为字典的键。
- 对字符串 “eat” 排序后得到 “aet”
- 对字符串 “tea” 排序后得到 “aet”
- 对字符串 “tan” 排序后得到 “ant”
- 对于相同的字母异位词,它们的排序后的字符串是相同的,因此会被分到同一组。
defaultdict(list)
用来创建一个默认值为列表的字典,这样在添加元素时无需先检查键是否存在。
- 如果 sorted_str 还没有出现在字典中,Python 会自动为它创建一个空列表。然后,我们将原始字符串 s 添加到这个列表中。
- 对 “eat” 排序,得到 “aet”,将 “eat” 加入到 anagrams[“aet”] 中,anagrams = {“aet”: [“eat”]}。
- 对 “tea” 排序,得到 “aet”,将 “tea” 加入到 anagrams[“aet”] 中,anagrams = {“aet”: [“eat”, “tea”]}。
- 对 “tan” 排序,得到 “ant”,将 “tan” 加入到anagrams[“ant”] 中,anagrams = {“aet”: [“eat”, “tea”], “ant”: [“tan”]}。
- 对 “ate” 排序,得到 “aet”,将 “ate” 加入到 anagrams[“aet”] 中,anagrams = {“aet”:[“eat”, “tea”, “ate”], “ant”: [“tan”]}。
- 对 “nat” 排序,得到 “ant”,将 "nat"加入到 anagrams[“ant”] 中,anagrams = {“aet”: [“eat”, “tea”, “ate”], “ant”:[“tan”, “nat”]}。
- 对 “bat” 排序,得到 “abt”,将 “bat” 加入到 anagrams[“abt”]中,anagrams = {“aet”: [“eat”, “tea”, “ate”], “ant”: [“tan”, “nat”],“abt”: [“bat”]}。
.values()
会返回 [[‘eat’, ‘tea’, ‘ate’], [‘tan’, ‘nat’], [‘bat’]]
2. 计数
- 将出现的字母次数的字母表作为键(one-hot编码)
- 将原str添加为键值
- 最后返回键值作为list
class Solution(object):def groupAnagrams(self, strs):""":type strs: List[str]:rtype: List[List[str]]""""""1.将出现的字母次数的字母表作为键(有点像one-hot编码,但次数可以大于2)2.将原str添加为键值3.最后返回键值作为list"""mp = defaultdict(list)for str in strs:# 创建字母表counts = [0] * 26for word in str:# 每个字母对应[0, 26]所出现的次数(ASCII码:ord)counts[ord(word) - ord("a")] += 1# unhashable type: 'list'# 字典的键必须是不可变类型,list可变,tuple不可变mp[tuple(counts)].append(str)return list(mp.values())
- 计数法:我们不再对字符串进行排序,而是通过一个包含26个元素的计数列表来记录每个字符串中每个字母的出现次数。字母的索引是通过
ord(char) - ord('a')
来计算的,这样就可以将每个字母映射到 0-25 的范围内。- 使用
tuple(count)
作为字典键:由于列表不可作为字典的键,我们将 count 转换为元组(tuple),作为字典的键。这样相同字母异位词的字符频率会生成相同的键,确保它们被分到同一组。defaultdict(list)
:这个数据结构使得当某个键第一次出现时,会自动创建一个空列表,无需显式地检查键是否已经存在。
对于单词 “eat”,char_count 是 [1, 0, 0, 0, 1, 0, …, 0, 1],转换为元组 (1, 0, 0, 0, 1, 0, …, 0, 1),作为键,将 “eat” 添加到字典 anagrams 中。
对于单词 “tea”,char_count 也是 [1, 0, 0, 0, 1, 0, …, 0, 1],转换为元组 (1, 0, 0, 0, 1, 0, …, 0, 1),它的字符频次和 “eat” 相同,因此将 “tea” 也添加到相同的组中。
对于单词 “tan”,char_count 是 [1, 0, 1, 0, 0, 0, …, 0],转换为元组 (1, 0, 1, 0, 0, 0, …, 0),作为键,它会被放到不同的组中,与 “nat” 和 “tan” 在同一组。