1
1
# Neetcode
2
2
class Solution :
3
3
def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
4
- results = []
5
- for i in strs :
6
- for j in range (strs .index (i ) + 1 , len (strs )):
7
- if sorted (i ) == sorted (strs [j ]):
8
- results .append ([i , strs [j ]])
9
- for i in results :
10
- for j in range (len (i ) - 1 ):
11
- if i [j ] == i [j + 1 ]:
12
- print (i [j ])
13
- return results
4
+
5
+ # # Step 1
6
+ # anagrams = defaultdict(list) # Initialize a dictionary to hold lists of anagrams
7
+
8
+ # # Iterate over each word in the list
9
+ # for word in strs:
10
+ # # Sort the characters of the word to use as the key
11
+ # sorted_word = ''.join(sorted(word))
12
+ # # Group anagrams together using the sorted word as the key
13
+ # anagrams[sorted_word].append(word)
14
+
15
+ # # Convert the dictionary values (which are lists of anagrams) to a list of lists
16
+ # return list(anagrams.values())
17
+
18
+ # # Step 2:
19
+ ans = collections .defaultdict (list )
20
+
21
+ for s in strs :
22
+ count = [0 ] * 26
23
+ for c in s :
24
+ count [ord (c ) - ord ("a" )] += 1
25
+ ans [tuple (count )].append (s )
26
+ return ans .values ()
14
27
15
28
16
29
# Leetcode
@@ -20,3 +33,26 @@ def groupAnagrams(self, strs):
20
33
:type strs: List[str]
21
34
:rtype: List[List[str]]
22
35
"""
36
+ # # Step 1
37
+ # anagrams = defaultdict(list) # Initialize a dictionary to hold lists of anagrams
38
+
39
+ # # Iterate over each word in the list
40
+ # for word in strs:
41
+ # # Sort the characters of the word to use as the key
42
+ # sorted_word = ''.join(sorted(word))
43
+ # # Group anagrams together using the sorted word as the key
44
+ # anagrams[sorted_word].append(word)
45
+
46
+ # # Convert the dictionary values (which are lists of anagrams) to a list of lists
47
+ # return list(anagrams.values())
48
+
49
+ # # Step 2:
50
+ ans = collections .defaultdict (list )
51
+
52
+ for s in strs :
53
+ count = [0 ] * 26
54
+ for c in s :
55
+ count [ord (c ) - ord ("a" )] += 1
56
+ ans [tuple (count )].append (s )
57
+ return ans .values ()
58
+
0 commit comments