[LeetCode] 49. Group Anagrams

2023. 1. 3. 13:44·BE/algorithm

문제 링크 

https://leetcode.com/problems/group-anagrams/description/

Intuition

  • 동일한 길이를 가지고 동일한 문자열 구성을 가져야 하는 anagram! 
    • 그럼 저번에 문제 풀이 했을 때 처럼 set을 사용해서 풀어볼까? 
    • 그런데 이 전 문제와 다르게 grouping 해야하는 문제니까 hash 를 써야할듯 

Approach

  • 단어가 3글자라고 주어진 input에서 3개 묶음의 단어가 다 있으리라고는 보장 X 
    • 있는 element를 기준으로 hash에 저장해서 확인해야함 
    • python에서 hash는? → dictionary! 
  • dict의 key 값은 정렬한 값으로 저장 → 모든 element가 정렬된 값을 기준으로 hasKey() operation을 해야하므로 
  • values() 는 strs의 element 리스트 
  • 각 strs의 element를 확인하고, sorted 된 결과값의
    • key가 존재한다면 → 해당 values 에 추가 
    • 없다면 → 새로운 group 추가 

Complexity

Time complexity:

  • O(NlogN) 

Space complexity:

Code

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        # create a dictionary for anagrams
        # sort word and check if that word exist in a set (anagram dictionary)
        # if yes, add, if not pass 

        anagrams = dict()
        for str in strs: 
            word = "".join(sorted(str))
            # if empty 
            if not anagrams: 
                anagrams[word] = [str]
            else: 
                if word in anagrams: 
                    anagrams[word].append(str)
                else: 
                    anagrams[word] = [str]
        
        return anagrams.values()

python 초보의 사소한 실수: sorted(string) 하면 그대로 정렬된 string 값을 내어주는줄 알았다..array가 return 값일줄은..!

 

 

저작자표시 비영리 변경금지 (새창열림)

'BE > algorithm' 카테고리의 다른 글

[Leetcode] 21. Merge Two Sorted Lists + 그림 풀이  (1) 2024.11.13
[LeetCode] 347. Top K Frequent Elements  (0) 2023.01.04
[LeetCode] 1. Two Sum  (0) 2023.01.03
[LeetCode] 242. Valid Anagram  (0) 2022.12.14
[LeetCode] 217. Contains Duplicate  (2) 2022.12.14
'BE/algorithm' 카테고리의 다른 글
  • [Leetcode] 21. Merge Two Sorted Lists + 그림 풀이
  • [LeetCode] 347. Top K Frequent Elements
  • [LeetCode] 1. Two Sum
  • [LeetCode] 242. Valid Anagram
bandal-gom
bandal-gom
Devops & Backend Developer | tech blog
  • bandal-gom
    yayz's devlog
    bandal-gom
  • 전체
    오늘
    어제
    • 분류 전체보기 (68)
      • DevOps (22)
        • devops (4)
        • cicd (2)
        • docker (2)
        • monitoring (2)
        • nginx (4)
        • cache (1)
        • aws (1)
        • etc (6)
      • BE (21)
        • BE (3)
        • design pattern (1)
        • data structure (0)
        • spring (1)
        • algorithm (12)
      • devlog (24)
        • TIL (17)
        • programming language (2)
        • conference (2)
        • etc (3)
      • IT Review (1)
  • 블로그 메뉴

    • about.
    • 개발👩‍💻
    • etc.
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    릿코드
    java
    algorithm
    알고리즘
    티스토리챌린지
    homelab
    키보드케이블
    hash
    키캡
    99클럽
    Kotlin
    jenkins
    프로그래머스
    leetcode 347
    코딩테스트준비
    Programmers
    오블완
    Python
    젠킨스
    문제풀이
    array
    알고리즘문제풀이
    NGINX
    노트북하기좋은카페
    모각코
    LeetCode
    til
    항해99
    time complexity
    개발자취업
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
bandal-gom
[LeetCode] 49. Group Anagrams
상단으로

티스토리툴바