Solution 1
class Solution:
“””
@param strs: the given array of strings
@return: The anagrams which have been divided into groups
“””
def groupAnagrams(self, strs):
# write your code here
dic = {}
for item in sorted(strs):
sortedItem = ”.join(sorted(item))
dic[sortedItem] = dic.get(sortedItem, []) + [item]
return dic.values()
Time Complexity: O ( N K log K ), where N N is the length of strs, and K K is the maximum length of a string in strs. Space Complexity: O ( N K ), the total information content stored in ans.
Solution 2
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
Solution 3
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) – ord(‘a’)] += 1
ans[tuple(count)].append(s)
return ans.values()
Time O ( N K ). Space O(N K).