给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
思路:
建立hashmap,key是sorted(s),values是排序后相同的s的list。
比如: [ “aet” : ["ate","eat","tea"], "ant": ["nat","tan"], "abt" : ["bat"] ]
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
hashmap = dict()
for s in strs:
t = "".join(sorted(s))
if t in hashmap:
hashmap[t].append(s)
else:
hashmap[t] = [s]
return hashmap.values()
#下面是丑陋的修改前版本
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
hashmap = dict()
for s in strs:
t = str(sorted(s))
# print s, t
if t in hashmap.keys():
hashmap[t] += " " + s
else:
hashmap[t] = s
# print hashmap
res = []
for key in hashmap.keys():
res.append([s for s in hashmap[key].split(" ")])
return res
以下是2019/6/13写的:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
record = dict()
for word in strs:
tmp = tuple(sorted(word))
# print tmp
if tmp in record:
record[tmp].append(word)
else:
record[tmp] = [word]
return [val for key, val in record.items()]
第二种思路:
还是hashmap,但是key不再是排序后的s,而是对s进行字符个数的统计,得到的list。
异曲同工,没有实现。