• leetcode49 字母异位词分组 哈希表 字典哈希 python dict


    此题考查对哈希表的考查

    给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

    字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。

    示例 1:

    输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

    自己实现的超时版本,超时的原因是 循环运用的次数太多,虽然是o(n),但是随着次数的增加,时间会非常慢。

    from collections import Counter

    def groupAnagrams(strs):

    count_list = []

    \#strs.sort()

    for i in strs:

    count_list.append(Counter(i))

    res_final=[]

    res=[]

    res_value=[]

    while len(count_list)>0:

    now=count_list[0]

    res.append(strs[0])

    count_list.remove(now)

    strs.remove(strs[0])

    count_strs=0

    for value in count_list:#循环次数+1

    if value==now:

    res.append(strs[count_strs])

    strs.remove(strs[count_strs])

    count_strs-=1

    count_strs+=1

    count_list=[]

    for i in strs:#循环次数+1

    count_list.append(Counter(i))

    res_final.append(res)

    res=[]

    return res_final

    \#strs=["","",""]

    strs=["eat","tea","tan","ate","nat","bat"]

    print(groupAnagrams(strs))

    看完题解后

    两个解题思路

    1.排序 2.计数

    使用python的dict数据结构很快就能实现 dict字典数据结构深入理解

    解法一 排序

    mp = collections.defaultdict(list)

    for st in strs:

    print(sorted(st))

    key = "".join(sorted(st))

    mp[key].append(st)

    return list(mp.values())

    解法二 计数

    mp = collections.defaultdict(list)

    for st in strs:

    counts = [0] * 26

    for ch in st:

    counts[ord(ch) - ord("a")] += 1 #需要将 list 转换成 tuple 才能进行哈希

    mp[tuple(counts)].append(st)

    print(mp.values())

    return list(mp.values())

  • 相关阅读:
    使用ffmpeg将mp4切片成ts slice 并生成m3u8命令,同时让IIS支持支持 m3u8
    C# 自动下移动光标 。winform 发送tab,在WPF中
    C# 获取当前程序路径方法整理
    Jeecg-Boot 2.0.0 版本发布,基于Springboot+Vue 前后端分离快速开发平台
    vue2.0源码-丰富的选项合并策略
    JavaScript 核心原理精讲
    前端性能优化
    Vue Router模式
    css3实现圆角三角形
    CSS动画
  • 原文地址:https://www.cnblogs.com/someonezero/p/16457066.html
Copyright © 2020-2023  润新知