Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
Subscribe to see which companies asked this question
本来写成下面的,超时了
这里面有两个优化,一个是使用get方法,可以免去判断
一个是,上来就相对strs进行排序
还有一个是,不要用set了,直接对每个字符串进行一个排序,这样就进行了一个归一化了
class Solution(object):
def groupAnagrams(self, strs):
dic = {}
strs.sort()
for i in strs:
ii = ''.join(sorted(i))
dic[ii] = dic.get(ii, []) + [i]
'''
if ii in keys:
dic[ii].append(i)
else:
keys.append(ii)
dic[ii] = [i]
'''
res = list(dic.values())
return res

本文介绍了一种有效的算法来解决将字符串数组中的同字母异序词进行分组的问题。通过先对字符串排序并利用哈希表进行分组,实现了高效地找到所有同字母异序词集合的方法。
2262

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



