【Leetcode】【python】Group Anagrams 字母异位词分组

题目大意

将所含字母相同,但排列顺序不同的字符串归并到一起。+

注意点:

所有输入的字符都是小写的
返回结果中每个组的字符串都要按照字典序排列

1
2
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]

解题思路

  1. 排序 2.存入dict

映射为{abc:abc,bac,acb}。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
temp_dict = {}
for word in strs:
word_key = "".join(sorted(word))
if word_key not in temp_dict:
temp_dict[word_key] = [word]
else:
temp_dict[word_key].append(word)
print temp_dict

result = []
for value in temp_dict.values():
result += [value]
return result

总结