[leetcode] 383. Ransom Note - Python

Heejun Kim·2022년 7월 7일
0

Coding Test

목록 보기
48/51

🔍 Problem

https://leetcode.com/problems/ransom-note/


📰 문제풀이

  • 제한 시간: 20분
  • 성공 여부: 성공

📃 Solving Process

  1. ransomNote가 magazine이 가진 알파벳으로 만들 수 있는지 확인하는 문제다.
  2. magazine이 가진 요소를 dictionary 구조로 저장한 뒤, ransomNote의 요소가 magazine에 있는지 확인한다.
  3. 2번의 확인 순서는 if 문의 순서와 같다.
  • 먼저 s가 magazine의 요소인지 확인한다.
  • 존재했던 요소지만 magazine이 가진 요소의 개수보다 많다면 해당 요소의 value는 0이기 때문에 magazine의 요소 개수만으로는 ransomeNote를 만들 수 없다.
  • 그게 아니라면 다음 확인을 위해 magazine의 요소가 가지는 value 값을 -1 한다.
  • 이때 첫 번째와 두 번째 분기 문을 or이나 and로 합칠 수 없다. 그 이유는 dict_maz에 없는 키값이 들어오면 첫 번째 조건은 에러를 발생시키지 않지만, 두 번째 조건은 에러를 발생시키기 때문이다.

💻 Code

# 초기 답안
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        dict_maz = dict()
        for s in magazine:
            dict_maz[s] = dict_maz.get(s, 0) + 1
        for s in ransomNote:
            if s not in dict_maz:
                return False
            if dict_maz[s] == 0:
                return False
            dict_maz[s] -= 1
            
        return True

# 개선 답안
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        dict_ran = collections.Counter(ransomNote)
        dict_maz = collections.Counter(magazine)

        for key, value in dict_ran.items():
            if key not in dict_maz or value > dict_maz[key]:
                return False
            
        return True

⏱ Time Complexity

  • dict_maz와 ransomNote를 탐색하는데 각각 O(N)O(N)만큼의 시간 복잡도가 발생한다.

💾 Space Complexity

  • 최악에는, magazine의 요소가 전부 다를 수 있기 때문에 O(N)O(N)의 공간복잡도가 예상된다.

0개의 댓글