Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
Python Solution 1:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for s in strs:
ctr = collections.Counter(s)
key = ''.join(sorted([key + str(ctr[key]) for key in ctr]))
d[key].append(s)
return d.values()
Python Solution 2:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for s in strs:
ctr = collections.Counter(s)
key = ''.join([c + str(ctr[c]) for c in string.ascii_lowercase if c in ctr])
d[key].append(s)
return d.values()
Python Solution 3:
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]
d = collections.defaultdict(list)
for s in strs:
key = 1
for c in s:
key *= prime[ord(c) - ord('a')]
d[key].append(s)
return d.values()
Summary:
- python solution 3 is acceptable in python.
LeetCode: 49. Group Anagrams





近期评论