Problem Link
https://leetcode.com/problems/group-anagrams/
Summary
정렬과 해시의 개념을 사용하는 문제
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.
- 혼자서 문제를 해결
- 힌트를 보고 해결
- 답을 보고 해결
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
archive = {}
for s in strs:
sort_s = ''.join(sorted(s))
if sort_s in archive:
archive[sort_s].append(s)
else:
archive[sort_s] = [s]
return list(archive.values())
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
[수정버전] 참고
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
archive = {}
for s in strs:
sort_s = ''.join(sorted(s))
archive[sort_s] = archive.get(sort_s, [])+[s]
return archive.values()