leetcode 49. 字母异位词分组

题目

思路

根据相同字符的字符串排序后相同,将排序后的字符当做对应的键,值为排序后字符串和键相同的源字符串

解题过程

1.长度为0,返回[[""]],长度为1或字符串有单个自负组成,则直接返回[str]

2.无上述情况下

  • 首先创建个列表s 来存储字符串排序后的数据(无重复)
  • 接着创建个空字典来进行映射

代码

python 复制代码
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        if len(strs)==0:
            return [[""]]
        elif len(strs)==1 or strs.count(strs[0])==len(strs):
            return [strs]
        else:
            s = []
            dict1 = {}
            for i in strs:
                t = ''.join(sorted(i))
                if t not in s:
                    s.append(t)
                    dict1[t]=[]
                # dict1[t] = dict1[t].append(i)
                dict1[t].append(i)
                
            return dict1.values()

改进

python 复制代码
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        if len(strs)==0:
            return [[""]]
        elif len(strs)==1 or strs.count(strs[0])==len(strs):
            return [strs]
        else:
            dict1 = {}
            for i in strs:
                t = ''.join(sorted(i))
                if t not in dict1:
                    dict1[t]=[]
                dict1[t].append(i)
            return dict1.values()

ps:

有个问题我不太能明白,dict1[t].append(i)这行代码我之前是使用dict1[t] = dict1[t].append(i),但会报错。我在之前已经有 dict1[t]=[],按理来说我只是往列表添加数据然后再赋值,可为什么会报错呢?(有知道的麻烦评论告知,在此先表示感谢)

知识点:

关于字符串内置函数 sorted()

相关推荐
天雪浪子1 分钟前
Python入门教程之赋值运算符
开发语言·python
站大爷IP29 分钟前
5个技巧写出专业Python代码:从新手到进阶的实用指南
python
纪元A梦31 分钟前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_44 分钟前
leetcode_21 合并两个有序链表
算法·leetcode·链表
hrrrrb1 小时前
【Python】字符串
java·前端·python
mark-puls1 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客1 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
大翻哥哥1 小时前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码
吃着火锅x唱着歌1 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun1 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划