49. Group Anagrams
49. Group Anagrams
0. 参考文献
序号 | 文献 |
---|---|
1 | [LeetCode] Group Anagrams 群组错位词 |
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
2. 思路
题目的要求是把错位词都分到一类里面。错位词的定义是,比如eat是aet的错位词。就是字母一样,但是排列组合的方式不一样。解法也很简单,把,每次字符出现的频率当做key计算。相同的key就分类到同一个数组里面。
3. 实现
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# 思路,每个单词的每个字符计算ascii码,如果是错位词,则ascii码的值相加肯定一样。用ascii的值做key保存结果
ret = []
r_map = {}
for e in strs:
tmp1 = [0]*128
for v in e :
tmp1[ ord(v) ] = tmp1[ ord(v) ] + 1
tmp2=""
for e1 in tmp1:
tmp2 = tmp2+str(e1)
if r_map.has_key(tmp2):
r_map[tmp2].append(e)
else:
r_map[tmp2] = [e]
for v in r_map.values():
ret.append(v)
return ret
编程光~