49. Group Anagrams
Medium
5197228Add to ListShare
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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""] Output: [[""]]
Example 3:
Input: strs = ["a"] Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lower-case English letters.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""
解题思路:枚举字符串,存进map里,
key:构造原串从低到高顺序
value:原串列表
时间复杂度:O(n*m) 其中n是数组长度,m是数组元素字符串的平均长度
空间复杂度:O(n*k) 其中n是数组长度
"""
if strs is None or len(strs) <= 0:
return strs
res = {}
for s in strs:
# 初始化26个小写英文字母出现次数0
count_list = [0] * (ord('z') - ord('a') + 1)
for c in s:
count_list[ord(c) - ord('a')] += 1
key = ""
for index, count in enumerate(count_list):
if count > 0:
key = key + (chr(ord('a') + index) * count)
result_list = res.get(key, [])
result_list.append(s)
res.__setitem__(key, result_list)
return list(res.values())
参考:https://leetcode.com/problems/group-anagrams/solution/
思路1:字符串排序作为key,value存原串list
Complexity Analysis
-
Time Complexity: O(NKlogK), where N is the length of
strs
, and K is the maximum length of a string instrs
. The outer loop has complexity O(N) as we iterate through each string. Then, we sort each string in O(KlogK) time. -
Space Complexity: O(NK), the total information content stored in
ans
.
# unhashable 可变对象
# 如list、dict、set:同值不同址,不同值同址
# hashable 不可变对象
# 如int、str、char、tuple:同值同址,不同值不同址
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = collections.defaultdict(list)
for s in strs:
# sorted(s) -> list 可变对象
# tuple(sorted(s)) -> tuple 不可变对象 可作为key
ans[tuple(sorted(s))].append(s)
return ans.values()
思路2:和我一样,利用标记次数减少排序需要的时间复杂度
不过代码写法比我精简许多。
class Solution:
def groupAnagrams(strs):
# 类似Map<T,List>
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()