LeetCode-Python-49. 字母异位词分组

本文介绍了一种高效的算法来解决字母异位词分组的问题,即如何将一个字符串数组中所有的字母异位词组合在一起。通过使用哈希映射的方法,文章详细解释了两种不同实现思路,并提供了具体的Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

思路:

建立hashmap,key是sorted(s),values是排序后相同的s的list。

比如: [ “aet” : ["ate","eat","tea"], "ant": ["nat","tan"], "abt" : ["bat"] ]

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        hashmap = dict()
        for s in strs:
            t = "".join(sorted(s))

            if t in hashmap:
                hashmap[t].append(s)
            else:
                hashmap[t] = [s]
            
        return hashmap.values()

#下面是丑陋的修改前版本
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        hashmap = dict()
        for s in strs:
            t = str(sorted(s))
            # print s, t
            if t in hashmap.keys():
                hashmap[t] += " " + s
            else:
                hashmap[t] = s
            # print hashmap
          
        res = []
        for key in hashmap.keys():
            res.append([s for s in hashmap[key].split(" ")])
            
        return res

以下是2019/6/13写的: 

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        record = dict()
        
        for word in strs:
            tmp = tuple(sorted(word))
            # print tmp
            if tmp in record:
                record[tmp].append(word)
            else:
                record[tmp] = [word]
        return [val for key, val in record.items()]

 

第二种思路:

还是hashmap,但是key不再是排序后的s,而是对s进行字符个数的统计,得到的list。

异曲同工,没有实现。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值