Python Algorithm
LeetCode
49. Group Anagrams
- Given an array of strings strs, group the anagrams together. You can return the answer in any order.
- Constraints
- 1 ≤ strs.length ≤ 10⁴
- 0 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# dictionary, key 값을 알파벳들을 정렬한 값으로 사용
d = defaultdict(list)
for word in strs:
key = "".join(sorted(word))
d[key].append(word)
return list(d.values())
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
str_dict = defaultdict(list)
for s in strs:
sorted_s = "".join(sorted(s))
str_dict[sorted_s].append(s)
return str_dict.values()
https://leetcode.com/problems/group-anagrams/
'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글
| Python - Algorithm #63 (0) | 2024.10.07 |
|---|---|
| Python - Algorithm #62 (0) | 2024.10.02 |
| Python - Algorithm #60 (0) | 2024.09.30 |
| Python - Algorithm #59 (0) | 2024.09.27 |
| Python - Algorithm #58 (0) | 2024.09.26 |