1
+ # Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.
2
+ # An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
3
+ # Example :
4
+ # Input: strs = ["act","pots","tops","cat","stop","hat"]
5
+ # Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]]
6
+
7
+ from typing import List
8
+ from collections import defaultdict
9
+
10
+ # Method 1: Sorting
11
+ class Solution1 :
12
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
13
+
14
+ res = defaultdict (list )
15
+
16
+ for s in strs :
17
+
18
+ sorted_s = "" .join (sorted (s ))
19
+ res [sorted_s ].append (s )
20
+
21
+ return list (res .values ())
22
+
23
+ # Method 2: Counting
24
+ class Solution2 :
25
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
26
+
27
+ res = defaultdict (list )
28
+
29
+ for word in strs :
30
+ count = [0 ] * 26
31
+
32
+ for c in word :
33
+ count [ord (c ) - ord ("a" )] += 1
34
+
35
+ key = tuple (count )
36
+ res [key ].append (word )
37
+
38
+ return list (res .values ())
0 commit comments