본문 바로가기
💻 LEETCODE

[LEETCODE] 383. Ransom Note

by 구라미 2022. 11. 22.

 

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.
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        dict_mag = dict()
        for s in magazine:
            dict_mag[s] = dict_mag.get(s, 0) +1
            print('dict_mag', dict_mag)
        for st in ransomNote:
            if st not in dict_mag:
                return False
            if dict_mag[st] == 0:
                return False
            dict_mag[s] -= 1
        return True

 

통과된 풀이

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        dict_ran = collections.Counter(ransomNote)
        dict_mag = collections.Counter(magazine)
        
        for key, value in dict_ran.items():
            if key not in dict_mag or value > dict_mag[key]:
                return False
        return True

 

신박한 풀이

완전 한줄짜리 풀이

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        return all( ransomNote.count(x) <= magazine.count(x)   for x in set(ransomNote) )

 

비슷한 원리인데 좀더 긴거

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        for i in set(ransomNote):
            if ransomNote.count(i) > magazine.count(i):
                return False
        return True

 

 

댓글