Skip to content

Commit 8607c5b

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 49 Group Anagrams
1 parent d30b00f commit 8607c5b

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
77
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
88
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
99
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
10+
- [49 Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
1011
- [55 Jump Game](https://leetcode.com/problems/jump-game/description/)
1112
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
1213
- [88 Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from collections import defaultdict
2+
from typing import List
3+
4+
5+
class Solution:
6+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
7+
"""
8+
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
9+
10+
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
11+
using all the original letters exactly once.
12+
"""
13+
res = defaultdict(list)
14+
for s in strs:
15+
count = [0] * 26
16+
for c in s:
17+
count[ord(c) - ord("a")] += 1
18+
res[tuple(count)].append(s)
19+
return list(res.values())

tests/test_49_group_anagrams.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._49_group_anagrams import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["strs", "expected"],
10+
argvalues=[
11+
(
12+
["eat", "tea", "tan", "ate", "nat", "bat"],
13+
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]],
14+
),
15+
([""], [[""]]),
16+
(["a"], [["a"]]),
17+
],
18+
)
19+
def test_func(strs: List[str], expected: List[List[str]]):
20+
groups = Solution().groupAnagrams(strs)
21+
assert groups == expected

0 commit comments

Comments
 (0)