본문 바로가기

LEETCODE

#49. Group Anagrams

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"]]

from collections import defaultdict
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic = defaultdict(list)
        for string in strs:
            dic[str(sorted(string))].append(string)
        return list(dic.values())
            #if dic[string] not in

https://leetcode.com/problems/group-anagrams/description/?envType=featured-list&envId=top-interview-questions?envType=featured-list&envId=top-interview-questions

'LEETCODE' 카테고리의 다른 글

#2. Add Two Numbers  (0) 2023.10.19
#36. Valid Sudoku  (1) 2023.10.17
#46. Permutations  (0) 2023.10.15
#22. Generate Parentheses (backtrack, stack)  (0) 2023.10.13
#19. Remove Nth Node From End of List  (0) 2023.10.13