광고
광고
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
이 문제는 문자열을 배열로 받아서 애너그램 단위로 묶어야 합니다.
애너그램은 문자의 위치를 바꿔서 다른 뜻을 가진 단어로 만든 것 입니다.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
aragrams = collections.defaultdict(list)
for word in strs:
aragrams[''.join(sorted(word))].append(word)
print(aragrams)
return list(aragrams.values())
받은 문자열을 정렬해서 딕셔너리 키로 저장해서 문제를 풀었습니다.
'파이썬 알고리즘 인터뷰 > 문제 풀이' 카테고리의 다른 글
백준 2002 추월 (2) | 2024.01.09 |
---|