题目内容
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()