LeetCode 383 Ransom Note (Python)

Posted by 小明MaxMing on May 3, 2020

题目

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.

解题思路

将勒索信和杂志的字符串都转成计数器,遍历勒索信中的每个字母,如果出现的次数都小于杂志中出现的次数则是True否则为False

代码

from collections import Counter
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ct_ransom = Counter(ransomNote)
        ct_magazine = Counter(magazine)
        for key in ct_ransom:
            if ct_ransom[key] > ct_magazine[key]:
                return False
        return True

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅