Skip to content

Instantly share code, notes, and snippets.

@yesidays
Created April 7, 2020 00:28
Show Gist options
  • Save yesidays/8b0f690516c5115a71050bb92a77c973 to your computer and use it in GitHub Desktop.
Save yesidays/8b0f690516c5115a71050bb92a77c973 to your computer and use it in GitHub Desktop.
Group anagrams - Leetcode
#https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3288/
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
keys = {}
result = []
sorted_list = [''.join(sorted(ele)) for ele in strs]
for i in range(len(strs)):
word = strs[i]
current = ''.join(sorted(word))
indexes = [i for i, x in enumerate(sorted_list) if x == current]
same = [strs[i] for i in indexes]
if word not in keys:
keys[current] = same
for value in keys.values():
result.append(value)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment