- Group Anagrams
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.
my thoughts:
1. iterate the list. convert each word to a letter:count key, store all word with same key in dd. return values of dd.
my solution:
**********292 ms
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dd = {}
for st in strs:
d = {}
for c in st:
d[c] = d.get(c, 0)+1
t = []
for k, v in sorted(d.items()):
t.append(k+str(v))
key = ''.join(t)
if key in dd:
dd[key].append(st)
else:
dd[key] = [st]
return list(dd.values())
my comments:
from other ppl's solution:
1. move efficient way to generator key, 199ms:
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
solution = {}
for string in strs:
key = "".join(sorted(string))
if key in solution:
solution[key].append(string)
else:
solution[key] = [string]
return list(solution.values())