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

相关推荐
好开心啊没烦恼10 分钟前
Python 数据分析:numpy,抽提,整数数组索引与基本索引扩展(元组传参)。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy·pandas
清幽竹客15 分钟前
Day 3:Python模块化、异常处理与包管理实战案例
python
岁忧17 分钟前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
BIYing_Aurora25 分钟前
【IPMV】图像处理与机器视觉:Lec13 Robust Estimation with RANSAC
图像处理·人工智能·算法·计算机视觉
菜包eo1 小时前
二维码驱动的独立站视频集成方案
网络·python·音视频
Yo_Becky1 小时前
【PyTorch】PyTorch预训练模型缓存位置迁移,也可拓展应用于其他文件的迁移
人工智能·pytorch·经验分享·笔记·python·程序人生·其他
yzx9910132 小时前
关于网络协议
网络·人工智能·python·网络协议
fangeqin2 小时前
ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
linux·python·ubuntu·openssl
martian6652 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习2 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法