Given an array of strings, group anagrams together. The function should return a list of lists, where each list contains strings that are anagrams of each other.
Hash Map and Sorted Strings
result
to store the final grouped anagrams.string_dict
to map sorted strings to their corresponding anagrams.string_dict
.string_dict
, append the original string to the list corresponding to that key.result
list.class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
result = []
string_dict = {}
for i in range(len(strs)):
current_string = strs[i]
sorted_string = "".join(sorted(strs[i]))
if sorted_string in string_dict:
string_dict[sorted_string].append(current_string)
else:
string_dict[sorted_string] = [current_string]
for key, value in string_dict.items():
result.append(value)
return result