관리 메뉴

솜씨좋은장씨

[leetCode] 383. Ransom Note (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 383. Ransom Note (Python)

솜씨좋은장씨 2020. 7. 19. 21:38
728x90
반응형

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

 

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:

  • You may assume that both strings contain only lowercase letters.

Solution

from collections import Counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        answer = True
        
        ran_list = list(ransomNote)
        mag_list = list(magazine)
        
        ran_cnt = dict(Counter(ran_list))
        mag_cnt = dict(Counter(mag_list))
        
        ran_keys = ran_cnt.keys()
        mag_keys = mag_cnt.keys()
        
        for r_key in ran_keys:
            if r_key not in mag_keys:
                answer = False
                break
            
            check = mag_cnt[r_key] - ran_cnt[r_key]
            if check < 0:
                answer = False
                break
        
            
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments