zoukankan      html  css  js  c++  java
  • 【LeetCode】49. Group Anagrams

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
    Return:

    [
      ["ate", "eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]

    解法1:

    把含有相同字母的字符串分之同一组,对每组的值sorted

    1 class Solution(object):
    2     def groupAnagrams(self, strs):
    3         """
    4         :type strs: List[str]
    5         :rtype: List[List[str]]
    6         """
    7         return [sorted(x) for _,x in itertools.groupby(sorted(strs, key=sorted),key=sorted)]

    解法2:

    把每一个含有相同字母的字符串散列到同一个key,然后对每个value排序即得。

     1 class Solution(object):
     2     def groupAnagrams(self, strs):
     3         """
     4         :type strs: List[str]
     5         :rtype: List[List[str]]
     6         """
     7         dd = collections.defaultdict(list)
     8         for s in strs:
     9             dd[tuple(sorted(s))].append(s)
    10         return map(sorted, dd.values())
  • 相关阅读:
    Mysql 从入门到遗忘
    Centos7开放及查看端口
    创建及修改数据库
    02_python是一种什么语言?
    03_SQL server数据类型
    02_关系数据库
    01_初识数据库
    kali 更新源
    01_Python简介
    Alertmanager高可用
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6498710.html
Copyright © 2011-2022 走看看