快乐的LeetCode --- 49. 字母异位词分组

题目描述:

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

示例:

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

解题思路1: 超出时间限制

  1. 通过字符内部的排序,找到不同字母组合的种类
  2. 依次遍历原有的字符列表,当出现的字母相同时,写进同一个列表中。

代码1:

class Solution(object):
    def groupAnagrams(self, strs):
        res = []
        if len(strs) <= 1: return [strs]
        for i in range(len(strs)):
            if ''.join(sorted(strs[i])) not in res:
                res.append(''.join(sorted(strs[i])))

        temp = []
        for j in range(len(res)):
            tem = []
            for string in strs:
                if ''.join(sorted(string)) == res[j]:
                    tem.append(string)
            temp.append(tem)
        return temp

解题思路2:

通过将字符串元素列为元组,作为字典的键,从而找出相对应的值来


代码2:

来自LeetCode官方

import collections
class Solution(object):
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for s in strs:
            ans[tuple(sorted(s))].append(s)
        return ans.values()

解题思路3:

当且仅当每个字符的出现的次数相同时,两个字符串是字母异位词。


代码3:

import collections
class Solution(object):
    def groupAnagrams(self, strs):
        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()

题目来源:

https://leetcode-cn.com/problems/group-anagrams

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值