Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 95a3e67

Browse files
#49: Group Anagrams
1 parent 878405f commit 95a3e67

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎Hash_Table/group_anagrams.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Given an array of strings strs, group the
2+
# anagrams
3+
# together. You can return the answer in any order.
4+
5+
6+
# Example 1:
7+
# Input: strs = ["eat","tea","tan","ate","nat","bat"]
8+
# Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
9+
10+
# Explanation:
11+
12+
# There is no string in strs that can be rearranged to form "bat".
13+
# The strings "nat" and "tan" are anagrams as they can be rearranged to
14+
# form each other.
15+
# The strings "ate", "eat", and "tea" are anagrams as they can be rearranged
16+
# to form each other.
17+
18+
# Example 2:
19+
# Input: strs = [""]
20+
# Output: [[""]]
21+
22+
# Example 3:
23+
# Input: strs = ["a"]
24+
# Output: [["a"]]
25+
26+
27+
# Constraints:
28+
29+
# 1 <= strs.length <= 104
30+
# 0 <= strs[i].length <= 100
31+
# strs[i] consists of lowercase English letters.
32+
33+
34+
from typing import List
35+
from collections import defaultdict
36+
class Solution:
37+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
38+
mpp = defaultdict(list)
39+
40+
for str in strs:
41+
key = ''.join(sorted(str))
42+
mpp[key].append(str)
43+
44+
return list(mpp.values())

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /