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.
내가 푼 것
-> 못품 ㅠㅠㅠㅠㅠ 주석으로 로직은 맞게 썼는데 함수를 뭘 써야하는지 도저히 생각이 안났음 ㅠㅠ 실제로도 모르는 거였음...그래도 풀 죽지말고 하자!
솔루션
import collections
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())
알아둘 것은 다음과 같다.
join()sorted() (vs sort())strs = ["eat", "tea", "tan", "ate", "nat", "bat"]for 루프의 첫번째 iteration (word = "eat"인 경우)는 다음과 같다.sorted(word)에서 "eat"를 ['a', 'e', 't']로 정렬''.join(sorted(word))를 통해 정렬된 각 문자를 "aet"로 이어붙임.anagrams["aet"].append("eat")가 anagrams에서 "aet"라는 key에다가 "eat"을 list로 이루어진 value에다가 추가시킨다. (최초에 angrams를 정의할 때 list가 되어있는 걸 상기하자. 그리고 알게된 사실 하나!! -> value를 리스트로 할 수 있따!!!!)values()로 반환꽤나 많은 걸 배운 문제였음. 특히 저 for 루프 돌아가는 게 처음엔 도대체 왜????? 이러다가 이해하니깐 신기했다 정말..오늘도 직관을 얻어서 좋았다.
끝.