Leetcode题库——49.字母异位词分组【##】
@author: ZZQ
@software: PyCharm
@file: leetcode49_groupAnagrams.py
@time: 2018/11/19 13:18
要求:给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
思路:ans用一个字典来表示,字典的键值是由26个字母组成的数组,来存储当前单词的哈希映射,值则是对应的这个单词。
最终的输出是ans的值。
例如:
对于ate,其键值为【1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0】
则在ans中,
ans = {【1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0】:【"ate","eat","tea"】
【1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0】:【"nat","tan"】
【1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0】:【"bat"】
}
import collections
class Solution():
def __init__(self):
pass
def groupAnagrams(self, 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()
CV小蜡肉