Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Example 1:
Input: strs = ["act","pots","tops","cat","stop","hat"]
Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]] Example 2:
Input: strs = ["x"]
Output: [["x"]] Example 3:
Input: strs = [""]
Output: [[""]]
In [8]:
def groupAnagrams(strs):
strDict = {}
for str in strs:
sortedStr = ''.join(sorted(str))
if sortedStr in strDict:
strDict[sortedStr].append(str)
else:
strDict[sortedStr] = [str]
return list(strDict.values())
In [9]:
groupAnagrams(["act","pots","tops","cat","stop","hat"])
Out[9]:
[['act', 'cat'], ['pots', 'tops', 'stop'], ['hat']]
In [4]:
print(list({1:[1,2]}.values()))
[[1, 2]]
In [7]:
sorted('cba')
Out[7]:
['a', 'b', 'c']