-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroup-Anagrams.py
94 lines (76 loc) · 2.1 KB
/
Group-Anagrams.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Group Anagrams
# 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.
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
output = {}
for i in strs:
word = "".join(sorted(i))
if word in output:
output[word].append(i)
else:
output[word] = [i]
return list(output.values())
# More optimal solutions
#Solution 1
# class Solution(object):
# def groupAnagrams(self, strs):
# """
# :type strs: List[str]
# :rtype: List[List[str]]
# """
# d = collections.defaultdict(list)
# for x in strs:
# xl = ''.join(sorted(x))
# d[xl].append(x)
# return d.values()
#Solution 2
# class Solution(object):
# def groupAnagrams(self, strs):
# """
# :type strs: List[str]
# :rtype: List[List[str]]
# """
# repo = {}
# res = []
# for word in strs:
# temp = ''.join(sorted(word))
# if temp in repo:
# res[repo[temp]].append(word)
# else:
# current_len = len(res)
# res.append([word])
# repo[temp] = current_len
# return res
#Solution 3
# class Solution(object):
# def groupAnagrams(self, strs):
# """
# :type strs: List[str]
# :rtype: List[List[str]]
# """
# answer=collections.defaultdict(list)
# for s in strs:
# answer[tuple(sorted(s))].append(s)
# return answer.values()
#Solution 4
# class Solution(object):
# def groupAnagrams(self, strs):
# ans = collections.defaultdict(list)
# for i in strs:
# ans[tuple(sorted(i))].append(i)
# return ans.values()