group_anagram

2022-12-14 浏览 (884)

group_anagram.py 源码

# 字母异位词分组
import collections
from typing import List


class Solution:

    # 排序后使用map进行分组
    def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]:
        m = {}
        for s in strs:
            k = str(sorted(s))
            if k in m:
                m[k].append(s)
            else:
                m[k] = [s]
        return list(m.values())

    # python更加tricky的一种写法
    def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:
        dic = collections.defaultdict(list)
        for s in strs:
            dic[tuple(sorted(s))].append(s)
        return list(dic.values())

你可能感兴趣的文章

array_intersection

array_intersection_ii

find_all_anagrams

  • 所属分类: 后端技术
  • 本文标签: 技术
  • 版权声明: 本文链接 https://seaxiang.com/blog/03972896bfb745cb8ce10cbf344a0594