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:

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

知识点:

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

相关推荐
@insist1239 分钟前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试
某人辛木18 分钟前
Web自动化测试
前端·python·pycharm·pytest
C+++Python40 分钟前
详细介绍一下Java泛型的通配符
java·windows·python
小帅热爱难回头2 小时前
编写Skill生成AI落地项目系统架构
python
diving deep2 小时前
脚本速览-python
开发语言·python
2601_951643773 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
AC赳赳老秦6 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
一只齐刘海的猫6 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1116 小时前
数据结构 | 八大排序
数据结构·算法·排序算法