Skip to content

Commit 915a1f9

Browse files
committed
Add #0049 Group Anagrams
1 parent ed3d0a8 commit 915a1f9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

#0049 Group Anagrams.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
class Solution:
4+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
5+
"""
6+
Group anagrams from a list of strings.
7+
8+
Parameters:
9+
strs (List[str]): A list of strings to be grouped.
10+
11+
Returns:
12+
List[List[str]]: A list of lists, where each sublist contains anagrams.
13+
"""
14+
groups = {} # Dictionary to store grouped anagrams
15+
16+
for s in strs:
17+
# Create a key by sorting the characters of the string and converting it to a tuple
18+
key = tuple(sorted(s))
19+
if key in groups:
20+
groups[key].append(s) # Add the string to the existing group
21+
else:
22+
groups[key] = [s] # Create a new group with the string
23+
24+
return list(groups.values()) # Return the list of grouped anagrams

0 commit comments

Comments
 (0)