https://leetcode.com/problems/group-anagrams/
Group Anagrams - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
문자열을 애너그램 단위로 묶어서 출력하는 문제이다.
애너그램을 판단하려면 정렬해서 비교하면 된다.
딕셔너리의 키 값을 정렬된 문자열, 밸류를 문자열로 해서 딕셔너리에 보관하면 애너그램 단위로 쉽게 묶어서 출력할 수 있다.
ex) abc bca cab는 모두 정렬하면 abc
abc: [abc, bca, cab]가 저장되게 됨
소스 코드
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = collections.defaultdict(list)
for str in strs:
s_str = ''.join(sorted(str))
dic[s_str].append(str)
return list(dic.values())
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 937. Reorder Data in Log Files [Python] (0) | 2022.07.21 |
---|---|
LeetCode - 344. Reverse String [Python] (0) | 2022.07.19 |
LeetCode - 125. Valid Palindrome [Python] (0) | 2022.07.19 |
LeetCode - Trapping Rain Water [Python] (0) | 2022.07.07 |
LeetCode - Two Sum [Python] (0) | 2022.07.07 |