Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active October 15, 2017 03:32
Show Gist options
  • Save cixuuz/663e5df8ef855c3bd5f932c049727311 to your computer and use it in GitHub Desktop.
Save cixuuz/663e5df8ef855c3bd5f932c049727311 to your computer and use it in GitHub Desktop.
[49. Group Anagrams] #leetcode
class Solution(object):
# O(nlgn*k) O(n*k)
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
groups = dict()
res = []
for s in strs:
sortedStr = "".join(sorted(s))
if sortedStr not in groups:
groups[sortedStr] = list()
groups[sortedStr].append(s)
return [v for _, v in groups.items()]
class Solution:
# O(n*k)
def groupAnagrams(strs):
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment