美文网首页
LC化元归一

LC化元归一

作者: SharlotteZZZ | 来源:发表于2018-11-07 23:26 被阅读0次

Catalog:
[Uber] LC 49 Group Anagram

[Uber] LC 49 Group Anagram
把相同字母排列不同的单词放在一起,返回list of list of strings.
方法一:sort作为base! 直接,Time Complexity: O(NKlogK),K是最长的string, 排序要KlogK.

class Solution(object):
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for s in strs:
            ans[tuple(sorted(s))].append(s)
        return ans.values()

方法二:Count26字母频率!

class Solution:
    def groupAnagrams(strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
        return ans.values()

utilizing unique prime multiplication,beat 91%

class Solution:
    def groupAnagrams(self,strs):
        primes = {'a': 2, 
                  'b': 3, 
                  'c': 5, 
                  'd': 7, 
                  'e': 11, 
                  'f': 13,
                  'g': 17,
                  'h': 19,
                  'i': 23,
                  'j': 29,
                  'k': 31,
                  'l': 37,
                  'm': 41,
                  'n': 43,
                  'o': 47,
                  'p': 53,
                  'q': 59,
                  'r': 61,
                  's': 67, 
                  't': 71,
                  'u': 73,
                  'v': 79,
                  'w': 83,
                  'x': 89,
                  'y': 97,
                  'z': 101
                 }
        
        
        ans = collections.defaultdict(list)
        
        for string in strs:
            product = 1
            
            for character in string:
                product = primes[character] * product
            
            ans[product].append(string)
            
        return ans.values()

You can also save prime numbers in an array and use character - 'a' to fetch the data!

相关文章

  • LC化元归一

    Catalog:[Uber] LC 49 Group Anagram [Uber] LC 49 Group Ana...

  • 《相元经》

    终极奥义: 相元一体交归自性化 无上恒一真信: 全人是爱信元体和体感通觉之浑同交归的无限化自本真 超越自化归途: ...

  • 力场

    引力区重磅产品【力场】,实名注册立即送3万LC(约210元),视频实名认证领取LC更简单。APP内更有多重玩法赚钱...

  • CentOS 常见错误 Failed to set locale

    输入locale指令,查看本地化配置项,LC_ALL和LC_CTYPE应该是错误的。 使用以下指令修改其配置:

  • LeetCode前两百刷题(1~20)

    leetcode lc1 & lc15& lc 16 & lc 18 多数之和问题 https://www.jia...

  • 何以名?

    弦而能识,可名之。 合同,约化,简并,曰归简。 简至常通曰化元,常通者四维适可。 名其玄元,成其道识。

  • DP真题

    骨骼清奇:LC 62LC 337 House Robber III LC 486 Predict the Win...

  • LC560/LC138如何机智正确地使用map

    LC138 复制链表 LC560

  • 算法笔记

    子序列 LC128. 最长连续序列 TOPK LC347. 最K个高频元素 LC347. 前K个高频元素 LC21...

  • 2019年最新的LC光模块产品类型汇总

    2019年最新的LC光模块产品类型汇总,先给大家介绍一下什么LC光模块?LC光模块指的是接口类型是LC的光模块,有...

网友评论

      本文标题:LC化元归一

      本文链接:https://www.haomeiwen.com/subject/byknzftx.html