LeetCode/NeetCodeRoadmap/Arrays_and_Hashing/49_Group_Anagrams.py
2023-09-07 20:49:02 -07:00

29 lines
949 B
Python

def groupAnagrams(strs: list[str])->list[str]:
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
strs_table = {}
# print(f'sorted string is {sorted(string)}')
for string in strs:
# Sort the string
sorted_string = ''.join(sorted(string))
print(f'sorted string is {sorted_string}')
# Place the sorted string into the dict table if it's not been seen
if sorted_string not in strs_table:
# Create new key if not seen before
strs_table[sorted_string] = []
# print(strs_table)
# print(strs_table)
# add string to key
strs_table[sorted_string].append(string)
return list(strs_table.values())
print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
print(groupAnagrams(["",""]))