Last active
October 15, 2017 03:32
-
-
Save cixuuz/663e5df8ef855c3bd5f932c049727311 to your computer and use it in GitHub Desktop.
[49. Group Anagrams] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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