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 5dcc2fd

Browse files
committed
Create group_anagrams.py
1 parent 48a87a6 commit 5dcc2fd

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎arrays_hashing/group_anagrams.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
(0)

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