forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup-anagrams.py
More file actions
36 lines (31 loc) · 1.05 KB
/
group-anagrams.py
File metadata and controls
36 lines (31 loc) · 1.05 KB
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
#https://leetcode.com/problems/group-anagrams/
class Solution(object):
def groupAnagrams(self, strs):
anagrams = collections.defaultdict(list)
for s in strs:
anagrams[''.join(sorted(s))].append(s)
return anagrams.values()
class Solution(object):
def groupAnagrams(self, strs):
anagrams = collections.defaultdict(list)
for s in strs:
hashkey = [0]*26
for c in s: hashkey[ord(c)-97] +=1
anagrams[''.join(hashkey)].append(s)
return anagrams.values()
"""
Time: O(NK), N is the number of strings, K is the number of characters in the string.
Space: O(NK).
"""
class Solution(object):
def groupAnagrams(self, strs):
anagrams = collections.defaultdict(list)
for s in strs:
anagrams[self.getKey(s)].append(s)
return anagrams.values()
def getKey(self, s):
key = ''
counts = collections.Counter(s)
for c in 'abcdefghijklmnopqrstuvwxyz':
key += counts[c]*c
return key