반응형
Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
- There is no string in strs that can be rearranged to form
"bat". - The strings
"nat"and"tan"are anagrams as they can be rearranged to form each other. - The strings
"ate","eat", and"tea"are anagrams as they can be rearranged to form each other.
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
group_anagram = defaultdict(list)
for word in strs :
sorted_word = ''.join(sorted(word))
group_anagram[sorted_word].append(word)
return list(group_anagram.values())
딕셔너리를 활용해서 정렬된 단어가 같은 단어면 word를 추가하는 로직으로 구성하였다. 이번 문제의 변수는 string 정렬을 어떻게 할 것인가. join 메소드를 활용해서 정렬을 할 수 있었다.
이번 문제는 아나그램의 특성을 잘 이해하고 있다면, 무난히 해결할 수 있는 문제라고 생각한다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 198.House Robber (1) | 2025.08.29 |
|---|---|
| [Leetcode/파이썬] 56. Merge Intervals (0) | 2025.08.14 |
| [Leetcode/파이썬] 228.Summary Ranges (0) | 2025.08.13 |
| [Leetcode/파이썬] 69. Sqrt(x) (5) | 2025.08.08 |
| [Leetcode/파이썬] 918. Maximum Sum Circular Subarray (0) | 2025.08.03 |