-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup-anagrams.py
More file actions
executable file
·46 lines (37 loc) · 948 Bytes
/
group-anagrams.py
File metadata and controls
executable file
·46 lines (37 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 00:27:30 2020
@author: johnoyegbite
"""
# SOLVED!
"""
Problem:
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.
"""
def groupAnagrams(strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
anagram_group = {}
for s in strs:
s_order = tuple(sorted(s))
if s_order in anagram_group:
anagram_group[s_order].append(s)
else:
anagram_group[s_order] = [s]
return anagram_group.values()
if __name__ == "__main__":
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(groupAnagrams(strs))