Skip to content

Commit e03738d

Browse files
committed
Update Logic
1 parent d20789b commit e03738d

File tree

1 file changed

+46
-10
lines changed

1 file changed

+46
-10
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
11
# Neetcode
22
class Solution:
33
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()
1427

1528

1629
# Leetcode
@@ -20,3 +33,26 @@ def groupAnagrams(self, strs):
2033
:type strs: List[str]
2134
:rtype: List[List[str]]
2235
"""
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

Comments
 (0)