Day038 - 383. Ransom Note

업데이트:

383. Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.


내 풀이

from collections import Counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        # ransomNote와 magazine을 Counter 객체화
        ran_dict = Counter(ransomNote)
        mag_dict = Counter(magazine)

        # ran_dict에 존재하는 key value들을 list로 할당받음
        check_list = ran_dict.keys()
        for i in check_list:
            # for loop을 순회하며 mag_dict에 존재하는 key의 등장횟수가 ran_dict보다 크거나 같으면 통과.
            if mag_dict[i] >= ran_dict[i]: 
                pass

            # 반대의 경우, 즉 magazine에 있는 글자로 ransomNote에 있는 글자를 충당하지 못할 때 False를 return.
            else:
                return False
        return True

# Time Complexity : \(O(N)\)


댓글남기기