49. Group Anagrams

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 in strs. 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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值