49. Group Anagrams
# Medium
Solution:
traverse all elements of strs
sort each word by letters
add to hashmap, the words composed with same letters will be mapped to same key-item
covert to
resultlist
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = {}
for x in strs:
tmp = sorted(x)
tmp = "".join(tmp)
if tmp not in d:
d[tmp] = [x]
else:
d[tmp].append(x)
result = []
for key in d.keys():
result.append(d[key])
return resultTime complexity = , if sorted() is , Space complesity =
list.sort() change the list, sorted(list) doesn't change the list.
list.reverse() change the list, reversed(list) doesn't change the list.
sorted(string) converts string to a list.
separator.join(list) means convert list to a string combining by separator. For example, "".join(['a', 'b', 'c']) = "abc".
Last updated
Was this helpful?