무냐의 개발일지
HT: Group Anagrams * 본문
👩💻 문제
You have been given an array of strings, where each string may contain only lowercase English letters. You need to write a function group_anagrams(strings) that groups the anagrams in the array together using a hash table (dictionary). The function should return a list of lists, where each inner list contains a group of anagrams.
For example, if the input array is ["eat", "tea", "tan", "ate", "nat", "bat"], the function should return [["eat","tea","ate"],["tan","nat"],["bat"]] because the first three strings are anagrams of each other, the next two strings are anagrams of each other, and the last string has no anagrams in the input array.
You need to implement the group_anagrams(strings) function and return a list of lists, where each inner list contains a group of anagrams according to the above requirements.
💡 풀이
def group_anagrams(strings):
my_dict = {}
for word in strings:
sorted_word = ''.join(sorted(word))
if sorted_word in my_dict:
my_dict[sorted_word].append(word)
else:
my_dict[sorted_word] = [word]
return list(my_dict.values())
✍️ 해설
같은 알파벳을 가진 단어끼리 리스트로 묶는 문제다.
딕셔너리가 필요하다!
[ 'eat' : ['eat', 'tea', 'ate']] 이런 식으로, 같은 알파벳 하에 같은 리스트를 묶어주고,
그 value들만 뽑아서 ans 에 append해준다는 아이디어!
이 때 앞의 key값은, 이 단어들을 sorted로 정렬해서 완전히 일치하는 값으로 넣어주면 된다!
(eat같은 경우는 aet 순서로 들어가겠지)
그리고 나서, 해당 단어의 sorted 버전이 딕셔너리의 key값에 존재하는지 확인하고, 있으면 append
없으면 새로운 리스트에 추가해준다.
최종적으로 그 dict의 value()를 리턴해준다. 이 때 주의할 점은 그대로 리턴 말고, list로 묶어서 리턴해야 한다는 점
my_dict.values()
>>> dict_values([8, 5, 6, 9, 7, 1])
list(my_dict.values())
>>> [8, 5, 6, 9, 7, 1]
그냥 뽑으면 말 그대로 dict_values라는 타입으로 나오게 되기 때문에,
앞에 list를 붙여서 리스트 형식으로 뽑아준다!!!
sorted('eat')
>>> ['a', 'e', 't']
글자를 sorted 하면 바로 자동으로 리스트형식으로 나오므로,
''.join() 을 통해 다시 string으로 만들어주는 작업을 한 번 거쳐야 함!
🥳 배운점
sorted는 리스트로 나오니까 다시 strings으로 만들어줘야 한다는 점
values를 리스트로 뽑으려면 list() 로 한번 감싸줘야 한다는 점
'LeetCode 코딩테스트' 카테고리의 다른 글
[기본개념] Graph 구조 (0) | 2024.07.01 |
---|---|
HT: Subarray Sum * (0) | 2024.07.01 |
[기본개념] Hash Table 구조 (0) | 2024.07.01 |
[기본개념] BST 기본 구조 (0) | 2024.07.01 |
BST: Convert Sorted List to Balanced BST (0) | 2024.07.01 |