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处理文件:Word导出PDF & 如何用Python从Word中提取数据:以处理简历为例
python·pdf·word
vvoennvv1 天前
【Python TensorFlow】 TCN-LSTM时间序列卷积长短期记忆神经网络时序预测算法(附代码)
python·神经网络·机器学习·tensorflow·lstm·tcn
nix.gnehc1 天前
PyTorch
人工智能·pytorch·python
Elias不吃糖1 天前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
z***3351 天前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
I'm Jie1 天前
从零开始学习 TOML,配置文件的新选择
python·properties·yaml·toml
铁手飞鹰1 天前
单链表(C语言,手撕)
数据结构·c++·算法·c·单链表
悦悦子a啊1 天前
项目案例作业(选做):使用文件改造已有信息系统
java·开发语言·算法
小殊小殊1 天前
【论文笔记】知识蒸馏的全面综述
人工智能·算法·机器学习
无限进步_1 天前
C语言动态内存管理:掌握malloc、calloc、realloc和free的实战应用
c语言·开发语言·c++·git·算法·github·visual studio