字母异位

题目:给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。例如

输入strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]

输出[[‘eat’, ‘tea’, ‘ate’], [‘tan’, ‘nat’], [‘bat’]]

思路:将每个单词的唯一的组成提取出来,再查看是否为字母异位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class :
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
strs_sorted = []
for i in range(len(strs)):
strs_sorted.append(''.join(sorted(strs[i])))
print(strs_sorted)

res_index = {}
for i in range(len(strs_sorted)):
if strs_sorted[i] in res_index.keys():
res_index[strs_sorted[i]].append(strs[i])
else:
res_index[strs_sorted[i]] = [strs[i]]
return list(res_index.values())


strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(Solution().groupAnagrams(strs))