[LeetCode] 49. Group Anagrams

题目内容

https://leetcode-cn.com/problems/group-anagrams/

Given an array of strings, group anagrams together.

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.
Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

题目思路

这道题目要用字典来完成。核心思路在于建立map映射,容易发生的错误点在于建立字典的value时,要用list格式才可以。建立map的方式有两种,第一种是对字符串中的字符进行排序(或者取集合排序),第二种是通过建立质数映射表,计算每一个字符串的乘法和进行映射。


程序代码

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        map={'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}
        num={}
        for i in strs:
            temp=1
            for j in i:
                temp*=map[j]
            if temp not in num:
                num[temp]=[i]
            else:
                num[temp].append(i)
        return num.values()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值