Open fockspaces opened 5 months ago
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
str_dict = defaultdict(list)
for s in strs:
mapping = [0] * 26
for c in s:
mapping[ord(c) - ord('a')] += 1
str_dict[tuple(mapping)].append(s)
return str_dict.values()
If the both strings are the same in the sorted char order, they are anagram each other. So we can sorted each elements in strs first, and then store each original strs by its ordered str as a key.