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()

相关推荐
Hgfdsaqwr1 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
TracyCoder1232 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
开发者小天2 小时前
python中For Loop的用法
java·服务器·python
老百姓懂点AI2 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
u0109272713 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837263 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义4 小时前
java基础十二
java·数据结构·算法
四维碎片4 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs4 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
喵手4 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列