Group Anagrams
字母异位词分组
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lower-case English letters.
约束条件中:strs[i] consists of lower-case English letters, 都是小写字母
1 排序法
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if len(strs)<2:
return [strs]
result={}
for s in strs:
# sort each string, and combine the sorted list into a string
#example:
#sorted("cba")->['a','b','c'];是排序后的
#‘’.join(sorted('cba'))->'abc'
temp=''.join(sorted(s))
#dict.get(x,y), x is the key, y is the default value
# if dict doesn't have the key x, it will return y as the value
# if dict has the key x, it will return the actual value of x
result[temp]=result.get(temp,[])+[s]
print(result.values())
return list(result.values())
(1)sort和sorted的对比
- sort 是应用在list上的方法,返回的是对已经存在的列表进行操作。没有返回值
- sorted是对所有可迭代的对象进行排序操作,返回的是一个新的list, 而不是在原来的基础上进行的操作。
sorted(‘cba’) 返回的是sorted后的列表,即:sorted(‘cba’)=[‘a’, ‘b’,‘c’]
(2)join
join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。str.join(sequence)
‘’.join(sorted(‘cba’)) 这样就得到了字符串’abc’,将其作为字典的key
(3)dict.get()
get()函数返回指定健的值
dict.get(key,default=None)
- key: 字典中要查找的键
- default: 如果指定键的值不存在时,则返回该默认值
(4)返回类型要求
因为要求返回的格式是:List[List(str)], 这个位置出了很多错。最开始的返回值,我写的是result.values(),但是一直通不过。最后发现result.values()的返回值的格式是List(str), 所以前面需要再加list,返回值是return list(result.values()),则通过。
2 哈希表法
class Solution:
#Hash table
#N is the size of strs
#K is the size of each element in strs
#Time complexity: O(NK)
#Space complexity: O(NK)
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if strs==None or len(strs)==1:
return [strs]
result={}
for s in strs:
count_tabel=[0]*26
for c in s:
count_tabel[ord(c)-ord('a')]+=1
# List can not be hash, but the key of dictionaay has to be hashable
# So we have to change list to tuple
temp=tuple(count_tabel)
result[temp]=result.get(temp,[])+[s]
return list(result.values())
(1) count_table=[0]*26
[0,0,…0] 共26个,分别对应26个字母
(2)维护一个数组,字母和ascii码对应
所以相减的是ord(‘a’)
(3) 字典的key必须是能hash的,但是list不能hash,做不了dict的key
- hashable: 可哈希的数据类型,即不可变的数据结构(字符串str, 元组tuple, 对象集objects). 哈希是将大体量数据转化为很小数据的过程,甚至仅仅就是一个数字,以便我们可以在固定的时间复杂度下插叙。
- 不可哈希unhashable:
同理,不可哈希的数据类型,即可变的数据结构 (字典dict, 列表list, 集合set)
本文介绍了如何解决LeetCode第49题——字母异位词分组的问题。文章通过两种方法详细讲解,包括排序法和哈希表法。排序法中,重点讲述了sort/sorted的区别、join方法的使用以及字典get()函数的应用。哈希表法则涉及计数表的创建、ASCII码对应以及字典中key的哈希性质。
461

被折叠的 条评论
为什么被折叠?



